题目描述

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true

示例 3:

输入: nums = [1,2,3,1,2,3], k = 2
输出: false

过程代码

package leetcode;

import java.util.Arrays;

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        for (int i=0; i<nums.length-1; i++) {
            for (int j=i+1; j<nums.length; j++) {
                if((nums[i] == nums[j]) && (j-i <= k)) {
                    return true;
                }
            }
        }
        
        return false;
    }
}

public class Test {
    public static void main(String[] args) {
        //int[] num = {1,2,3,1}; // k = 3, 存在相同元素测试
        int[] num = {1,2,3,1,2,3}; // k = 2, 不存在相同元素测试
        Solution1 solution = new Solution1();
        System.out.println(solution.containsNearbyDuplicate(num,2));
    }
}

LeetCode_219:存在重复元素 II

优化代码

用空间换取时间:

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet<Integer>();
        for (int i = 0;i < nums.length;i++) {
            if (i > k) {
                set.remove(nums[i-k-1]);
            }
            if (!set.add(nums[i])) {
                return true;
            }
        }
        return false;
    }
}

LeetCode_219:存在重复元素 II

相关文章:

  • 2021-11-04
  • 2021-06-18
  • 2021-09-12
  • 2022-02-22
  • 2021-05-10
  • 2021-10-05
  • 2022-12-23
猜你喜欢
  • 2021-09-21
  • 2021-09-20
  • 2021-09-05
  • 2022-01-02
  • 2021-10-21
  • 2021-07-05
  • 2022-12-23
相关资源
相似解决方案