| comments | true | |
|---|---|---|
| difficulty | 简单 | |
| edit_url | https://github.com/doocs/leetcode/edit/main/solution/2200-2299/2239.Find%20Closest%20Number%20to%20Zero/README.md | |
| rating | 1256 | |
| source | 第 76 场双周赛 Q1 | |
| tags |
|
给你一个长度为 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
我们定义一个变量
遍历结束后返回答案即可。
时间复杂度
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans, d = 0, inf
for x in nums:
if (y := abs(x)) < d or (y == d and x > ans):
ans, d = x, y
return ansclass Solution {
public int findClosestNumber(int[] nums) {
int ans = 0, d = 1 << 30;
for (int x : nums) {
int y = Math.abs(x);
if (y < d || (y == d && x > ans)) {
ans = x;
d = y;
}
}
return ans;
}
}class Solution {
public:
int findClosestNumber(vector<int>& nums) {
int ans = 0, d = 1 << 30;
for (int x : nums) {
int y = abs(x);
if (y < d || (y == d && x > ans)) {
ans = x;
d = y;
}
}
return ans;
}
};func findClosestNumber(nums []int) int {
ans, d := 0, 1<<30
for _, x := range nums {
if y := abs(x); y < d || (y == d && x > ans) {
ans, d = x, y
}
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}function findClosestNumber(nums: number[]): number {
let [ans, d] = [0, 1 << 30];
for (const x of nums) {
const y = Math.abs(x);
if (y < d || (y == d && x > ans)) {
[ans, d] = [x, y];
}
}
return ans;
}