219. Contains Duplicate II

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.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
难度:easy
题目:给定一整数数组和一整数K,找出是否存在两个不同的下标使用得nums[i]=nums[j]并且i与j之差的绝对值小于等于k.
思路:hashmap
Runtime: 9 ms, faster than 81.45% of Java online submissions for Contains Duplicate II.Memory Usage: 41 MB, less than 77.21% of Java online submissions for Contains Duplicate II.
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> mii = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
if (mii.containsKey(nums[i]) && i – mii.get(nums[i]) <= k) {
return true;
}
mii.put(nums[i], i);
}

return false;
}
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理