Leet Code OJ 219. Contains Duplicate II [Difficulty: Easy]
Posted brucemengbm
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leet Code OJ 219. Contains Duplicate II [Difficulty: Easy]相关的知识,希望对你有一定的参考价值。
题目:
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 difference between i and j is at most k.
翻译:
给定一个整数数组和一个整数k。找出是否存在下标i,j使得nums[i] = nums[j]。同一时候i,j的差值小于等于k。
分析:
遍历数组。使用map存储每一个值近期一次出现的下标。
代码:
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
Integer value=map.get(nums[i]);
if(value!=null&&i-value<=k){
return true;
}else{
map.put(nums[i],i);
}
}
return false;
}
}
以上是关于Leet Code OJ 219. Contains Duplicate II [Difficulty: Easy]的主要内容,如果未能解决你的问题,请参考以下文章
Leet Code OJ 1. Two Sum [Difficulty: Easy]
Leet Code OJ 223. Rectangle Area [Difficulty: Easy]
Leet Code OJ 338. Counting Bits [Difficulty: Easy]
Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]