Skip to content

Latest commit

 

History

History
135 lines (102 loc) · 2.65 KB

File metadata and controls

135 lines (102 loc) · 2.65 KB

English Version

题目描述

给你一个长度为 n 的整数数组 nums ,请你返回 nums 中最 接近 0 的数字。如果有多个答案,请你返回它们中的 最大值 。

 

示例 1:

输入:nums = [-4,-2,1,4,8]
输出:1
解释:
-4 到 0 的距离为 |-4| = 4 。
-2 到 0 的距离为 |-2| = 2 。
1 到 0 的距离为 |1| = 1 。
4 到 0 的距离为 |4| = 4 。
8 到 0 的距离为 |8| = 8 。
所以,数组中距离 0 最近的数字为 1 。

示例 2:

输入:nums = [2,-1,1]
输出:1
解释:1 和 -1 都是距离 0 最近的数字,所以返回较大值 1 。

 

提示:

  • 1 <= n <= 1000
  • -105 <= nums[i] <= 105

解法

Python3

class Solution:
    def findClosestNumber(self, nums: List[int]) -> int:
        ans, d = 0, 1000000
        for v in nums:
            if (t := abs(v)) < d or (t == d and v > ans):
                ans, d = v, t
        return ans

Java

class Solution {
    public int findClosestNumber(int[] nums) {
        int ans = 0, d = 1000000;
        for (int v : nums) {
            int t = Math.abs(v);
            if (t < d || (t == d && v > ans)) {
                ans = v;
                d = t;
            }
        }
        return ans;
    }
}

C++

class Solution {
public:
    int findClosestNumber(vector<int>& nums) {
        int ans = 0, d = 1e6;
        for (int& v : nums) {
            int t = abs(v);
            if (t < d || (t == d && v > ans)) {
                ans = v;
                d = t;
            }
        }
        return ans;
    }
};

Go

func findClosestNumber(nums []int) int {
	ans, d := 0, 1000000
	for _, v := range nums {
		t := abs(v)
		if t < d || (t == d && v > ans) {
			ans, d = v, t
		}
	}
	return ans
}

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

TypeScript

...