题目原文:
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 jis at most k.
题目大意:
给一个数组nums和整数K,问是否存在两个下标i和j,使得nums[i]=nums[j],并且|i-j|≤k。
题目分析:
使用HashMap记录一组key-value对,其中key为数组中元素的值,value为所在下标。
当key不重复时加入HashMap即可,如果发现了重复的key,则判断当前数组下标和value值(分别对应题干中的i和j)绝对值是否≤k。
源码:(language:java)
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++) {
if(map.containsKey(nums[i]) && Math.abs(i-map.get(nums[i]))<=k)
return true;
else
map.put(nums[i],i);
}
return false;
}
}
成绩:
16ms,beats 5.31%,众数14ms,30.23%
cmershen的碎碎念:
使用了trivial的解法因此成绩低于平均值(但不算太差),可能是HashMap浪费了开销,discuss中似乎有基于快排的解法,有待日后研读。