Notice
Recent Posts
Recent Comments
Today
Total
01-10 22:06
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[LEETCODE] 1822. Sign of the Product of an Array ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด/PS

[LEETCODE] 1822. Sign of the Product of an Array

WonderJay 2022. 10. 12. 14:57
728x90
๋ฐ˜์‘ํ˜•
SMALL

https://leetcode.com/

TITLE : 1822. Sign of the Product of an Array

Description : There is a function signFunc(x) that returns:

  • 1 if x is positive.
  • -1 if x is negative.
  • 0 if x is equal to 0.

You are given an integer array nums. Let product be the product of all values in the array nums.

Return signFunc(product).

 

Example 1:

Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1

Example 2:

Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0

Example 3:

Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1

 

Constraints:

  • 1 <= nums.length <= 1000
  • -100 <= nums[i] <= 100

array ์— ๋“ค์–ด์žˆ๋Š” ์›์†Œ๋“ค์˜ ๊ณฑ์˜ ๋ถ€ํ˜ธ์— ๋”ฐ๋ผ -1, 0, 1 ์„ ์ถœ๋ ฅํ•ด์ฃผ๋ฉด ๋œ๋‹ค. ์‚ฌ์‹ค ์ฒ˜์Œ์—๋Š” ์‹ค์ œ๋กœ ๊ทธ๋ƒฅ ๋‹ค ๊ณฑํ•ด์„œ ๋ถ€ํ˜ธ๋ฅผ ๋ฝ‘์•„๋‚ด๋ฉด ๋˜๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ, Constraints ๋ฅผ ๋ณด๋ฉด ์›์†Œ์˜ ํฌ๊ธฐ๋Š” 100, ๊ฐœ์ˆ˜๋Š” 1000 ์ด ๋“ค์–ด์˜จ๋‹ค๊ณ  ์น˜๋ฉด long long ํ˜•์œผ๋กœ๋„ ๋‹ค ํ‘œํ˜„ํ•˜์ง€ ๋ชปํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ๊ตฌํ•ด์•ผํ•˜๋Š” ๊ฑฐ๋Š” ๋ถ€ํ˜ธ์ด๊ณ , ๋ถ€ํ˜ธ๋Š” ์Œ์ˆ˜๊ฐ€ ๋ช‡๊ฐœ ์žˆ๋Š”์ง€์— ๋”ฐ๋ผ์„œ ๊ฒฐ์ •๋œ๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ ์Œ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ณ , ์Œ์ˆ˜๊ฐ€ ์ง์ˆ˜์ด๋ฉด 1, ์•„๋‹ˆ๋ฉด -1 ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ( ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋‹ค๊ฐ€ array ์˜ ์›์†Œ๊ฐ€ 0 ์ด ๋‚˜์˜ค๋ฉด ๋ฐ”๋กœ 0 ์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค. )

 

์‹œ๊ฐ„ ๋ณต์žก๋„ : O(N)

 

[C++]

class Solution {
public:
    int arraySign(vector<int>& nums) {
        int positive_cnt = 0; int negative_cnt = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == 0) return 0;
            else if (nums[i] > 1) positive_cnt++;
            else if (nums[i] < 0) negative_cnt++;
        }
        if (negative_cnt % 2 == 1) return -1;
        else return 1;
    }
};

 

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments