Contains Duplicate II

https://www.lintcode.com/problem/contains-duplicate-ii/description

public class Solution {
    /**
     * @param nums: the given array
     * @param k: the given number
     * @return: whether there are two distinct indices i and j in the array such that nums[i] =
     * nums[j] and the absolute difference between i and j is at most k
     */
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        // Write your code here
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            for (int j = i + 1; j <= i + k && j < nums.length; j++) {
                if (num == nums[j]) {
                    return true;
                }
            }
        }
        return false;
    }
}

你可能感兴趣的:(Contains Duplicate II)