[leetcode]219.Contains Duplicate II
Posted shinjia
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]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
解法
思路
直接用hashmap即可,以nums[i]为键,以i为值
代码
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i]))
if(i-map.get(nums[i]) <= k) return true;
map.put(nums[i], i);
}
return false;
}
}
以上是关于[leetcode]219.Contains Duplicate II的主要内容,如果未能解决你的问题,请参考以下文章
219. Contains Duplicate II - LeetCode
LeetCode 219 Contains Duplicate II
[leetcode-219-Contains Duplicate II]
leetcode219 Contains Duplicate2