java为什么我的代码在查找重复项时出错?
我正试图解决这个Leetcode问题https://leetcode.com/problems/contains-duplicate-ii/
我不知道为什么我的代码不正确。我一直在关注这个问题,并试图尽可能地把它写出来,但没有成功
有人能指出我做错了什么吗
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
boolean flag = false;
int ans = 0;
for(int i = 0; i < nums.length; i++) {
for(int j = i + 1; j < nums.length; j++) {
if(nums[i] == nums[j]) {
flag = true;
}
if(flag) {
ans = Math.abs(nums[i] - nums[j]);
}
if(ans <= k) {
return true;
}
}
}
return false;
}
}
# 1 楼答案
问题出在哪里
您正在检查数字的值是否为
<= k
,而应该检查索引按以下步骤进行:
# 2 楼答案
你可以初始化
int ans = 0;
让我们假装i = 0; j = 1;
nums[i] != nums[j] /// flag still == false.
然后检查ans<;=K 由于ans仍然为0,所以该键将更低
您应该在此处添加额外的支票:
此外,你称之为数学。abs()在数字上,而不是索引上