代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
给你一个长度为 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
我们定义一个变量 $d$ 来记录当前最小的距离,初始时 $d=\infty$。然后我们遍历数组,对于每个元素 $x$,我们计算 $y=|x|$,如果 $y \lt d$ 或者 $y=d$ 且 $x \gt ans$,我们就更新答案 $ans=x$ 和 $d=y$。
遍历结束后返回答案即可。
时间复杂度 $O(n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。
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 ans
class 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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。