有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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;
    }
}

共 (2) 个答案

  1. # 1 楼答案

    问题出在哪里

    您正在检查数字的值是否为<= k,而应该检查索引

    按以下步骤进行:

    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]) {
                if( Math.abs(i - j) <= k) return true;
             }
          }   
       }
       return false;
    }
    
  2. # 2 楼答案

    你可以初始化int ans = 0; 让我们假装i = 0; j = 1; nums[i] != nums[j] /// flag still == false.

    然后检查ans<;=K 由于ans仍然为0,所以该键将更低

    您应该在此处添加额外的支票:

     if(ans != 0 && ans <= k) {
         return true;
     }
    

    此外,你称之为数学。abs()在数字上,而不是索引上