2239. Find Closest Number to Zero

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int findClosestNumber(vector<int>& nums) {
int ret = nums[0];
for(int n:nums){
if(abs(n) <= abs(ret) ) {
if(abs(n)==abs(ret) && n>0) ret= n;
// else if(abs(n) == abs(ret)) continue;
else if(abs(n) < abs(ret)) ret = n;
}
}
return ret;
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)