Given an array of integers and an integerk, find out whether there are two distinct indicesiandjin the array such thatnums[i] = nums[j]and the difference betweeniandjis at mostk.
這道題還是很簡單的。沒啥可說的。直接用hashmap就可以做了,借助containsKey(),get()還有put()。
代碼如下。~
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer,Integer>test=new HashMap<>(); for(int i=0;i<nums.length;i++){ if(test.containsKey(nums[i])){ int diff=i-test.get(nums[i]); if(diff<=k){ return true; } } test.put(nums[i],i); } return false; }}新聞熱點
疑難解答