157.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.
给定整数数组和整数k,找出数组中是否存在两个不同的索引i和j,使得nums [i] = nums [j]并且i和j之间的绝对差值最多为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值和位置的映射
1 class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 Map<Integer,Integer> map=new HashMap<>(); 4 for(int i=0;i<nums.length;i++){ 5 if(map.containsKey(nums[i])) 6 if(i-map.get(nums[i])<=k) 7 return true; 8 map.put(nums[i],i); 9 } 10 return false; 11 } 12 }
方法二:hashset无法增加新的值时,说明有重复元素
1 class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 Set set=new HashSet(); 4 for(int i=0;i<nums.length;i++){ 5 if(i>k) set.remove(nums[i-k-1]); 6 if(!set.add(nums[i])) return true; 7 } 8 return false; 9 } 10 }
详解: