Why's my code wrong when looking for duplicates? : <p>I'm trying to solve this Leetcode problem <a href="https://leetcode.com/problems/contains-duplicate-ii/" rel="nofollow noreferrer">https://leetcode.com/problems/contains-duplicate-ii/</a></p>

<p>I'm not sure why my code's incorrect.  I've followed the problem and tried to write it out as best as I could but it didn't work.</p>

<p>Can someone point out what I did wrong?</p>

<pre><code>class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        boolean flag = false;
        int ans = 0;

        for(int i = 0; i &lt; nums.length; i++) {
            for(int j = i + 1; j &lt; nums.length; j++) {
                if(nums[i] == nums[j]) {
                    flag = true;
                }

                if(flag) {
                    ans = Math.abs(nums[i] - nums[j]);
                }

                if(ans &lt;= k) {
                    return true;
                }
            }   
        }
        return false;
    }
}
</code></pre>
