2239 找到最接近 0 的数字

·   ·   ·   ·

  ·   ·


题目链接

2239. 找到最接近 0 的数字

分析

遍历判断即可

代码实现

class Solution {
public:
    int findClosestNumber(vector<int>& nums) {
        int ans = nums[0];
        for(int i : nums) {
            if(abs(i) < abs(ans) || abs(i) == abs(ans) && i > ans)
                ans = i;
        }
        return ans;
    }
};

复杂度分析

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$