LeetCode—1822

Approach

# 不需要真的計算,只要記錄正數負數就好
No need to compute the exact sum, just track the sign (positive or negative).

Time Complexity

# n = length of nums
O(n)

Space Complexity

# n = length of nums
O(n)

Code

class Solution {
public:
    int arraySign(vector<int>& nums) {
        int l = nums.size(), ans = 1;

        for (int i = 0 ; i < l ; i++) {
            if (nums[i] == 0) {
                return 0;
            }
            else {
                if (nums[i] >= 1) {
                    ans *= 1;
                }
                else {
                    ans *= -1;
                }
            }
        }

        if (ans >= 1) {
            return 1;
        }
        else{
            return -1;
        }
    }
};