-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1822-Sign_of_the_Product_of_an_Array.cpp
More file actions
98 lines (88 loc) · 2.24 KB
/
1822-Sign_of_the_Product_of_an_Array.cpp
File metadata and controls
98 lines (88 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*******************************************************************************
* 1822-Sign_of_the_Product_of_an_Array.cpp
* Billy.Ljm
* 02 May 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/sign-of-the-product-of-an-array/
*
* 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).
*
* ===========
* My Approach
* ===========
* We just have to calculate the sign of the product, not the numeric value.
* Thus, we iterate through the array and if the integer is positive we don't
* flip the sign, if it's negative we flip, and if it's zero we immediately
* return.
*
* This has a time complexity of O(n) and space complexity of O(1), where n is
* the length of the array.
******************************************************************************/
#include <iostream>
#include <vector>
/**
* Solution
*/
class Solution {
public:
/**
* Return the sign of the product of an integer array
*
* @param nums integer array to multiply
*
* @return 1 if the product is positive, -1 if negative, 0 if zero
*/
int arraySign(std::vector<int>& nums) {
bool ispos = true;
for (int num : nums) {
if (num == 0) { // if zero, immediately return
return 0;
}
else if (num < 0) { // if negative, flip sign
ispos = !ispos;
}
// if positive, don't flip sign
}
return ispos ? 1 : -1;
}
};
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (int i = 0; i < v.size(); i++) {
os << v[i] << ",";
}
os << "\b]";
return os;
}
/**
* Test cases
*/
int main(void) {
Solution sol;
std::vector<int> nums;
// test case 1
nums = { -1, -2, -3, -4, 3, 2, 1 };
std::cout << "arraySign(" << nums << ") = " << sol.arraySign(nums) << std::endl;
// test case 2
nums = { 1, 5, 0, 2, -3 };
std::cout << "arraySign(" << nums << ") = " << sol.arraySign(nums) << std::endl;
// test case 2
nums = { -1, 1, -1, 1, -1 };
std::cout << "arraySign(" << nums << ") = " << sol.arraySign(nums) << std::endl;
return 0;
}