- Today
- Total
- ์์์ ๋ ฌ
- java
- ๋ฌธ๋ฒ
- ๊ตฌํ
- ๋ฒจ๋งํฌ๋
- database
- ๋ฐฑ์๋
- ๋ค์ต์คํธ๋ผ
- spring
- ์๋ฐ์์ ์
- MST
- pytorch
- OOP
- Graph
- ํ๋ก๊ทธ๋๋จธ์ค
- dp
- Algorithm
- ๋ฐ์ดํฐ๋ฒ ์ด์ค
- PS
- BFS
- ์๋ฐ
- CS
- array
- ๋ฐฑ์ค
- tree
- ์ธํด
- leetcode
- ์กธ์ ์ํ
- ์๋ฃ๊ตฌ์กฐ
- ๊ทธ๋ฆฌ๋
Partially Committed
[LEETCODE] 1822. Sign of the Product of an Array ๋ณธ๋ฌธ
[LEETCODE] 1822. Sign of the Product of an Array
WonderJay 2022. 10. 12. 14:57
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;
}
};
'๐ฅ Algorithm || ๋ฌธ์ ํ์ด > PS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LEETCODE] 202. Happy Number (0) | 2022.10.12 |
---|---|
[LEETCODE] 1502. Can Make Arithmetic Progression From Sequence (0) | 2022.10.12 |
[LEETCODE] 1779.Find Nearest Point That Has the Same X or Y Coordinate (0) | 2022.10.11 |
[LEETCODE] 1281. Subtract the Product and Sum of Digits of an Integer (0) | 2022.10.10 |
[LEETCODE] 191.Number of 1 Bits (0) | 2022.10.10 |