2
头图

There are duplicate elements II

Title description: Given an integer array and an integer k, judge whether there are two different indexes i and j in the array, so that nums [i] = nums [j], and the absolute value of the difference between i and j is at most k .

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/contains-duplicate-ii/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Brute force method
Double loop, the range of the outer loop i is 0~nums.length-2 , the range of the inner loop j is i+1~(nums.length and j<=i+k), the judgment condition in the loop body is that the two values are equal, if they are equal , It returns true. After the loop ends, if there is no matching integer pair, it returns false.
public class LeetCode_219 {
    /**
     * 暴力破解法
     * @param nums
     * @param k
     * @return
     */
    public static boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length < 2) {
            return false;
        }
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length && j <= i + k; j++) {
                if (nums[i] == nums[j] && (j - i) <= k) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 3, 1};
        System.out.println(containsNearbyDuplicate(nums, 3));
    }
}
[Daily Message] The meaning of hard work is: in the days to come, when you look around, everything you like will be what you like.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!