219. Contains Duplicate II

xiaoxiao2021-02-28  13

Given an array of integers and an integer k, find out 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.

其实又是水题,跟上一题没变多少,不过这里给了个k,要求数组中相同的element的index之差小于k

public boolean containsDuplicate(int[] nums, int k) { HashMap<Integer, Integer> hm = new HashMap<>(); int x = 0; for (int i=0; i<nums.length; i++) { x = nums[i]; if (hm.containsKey(x)) { if ((i - hm.get(x)) <= k) return true; } hm.put(x, i); } return false; }要注意的就是跟上题是判断是否存在同个数字不同,这里同个数字的index之差可能有大有小,所以先全存到map里去过一遍,如果有符合的就return true
转载请注明原文地址: https://www.6miu.com/read-2450240.html

最新回复(0)