LeetCode OJ 219.Contains Duplicate 2

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[i] = nums[j]出现的范围作出了规定,不是全局的,而是要求|i-j|<=k;

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         Map<Integer,Integer> map = new HashMap<>(0);
 4         
 5         for(int i=0; i<nums.length; i++){
 6             if(map.containsKey(nums[i])){
 7                 if(i-map.get(nums[i])<=k) return true;
 8             }
 9             if(map.size()>k) map.remove(nums[i-k]);
10             map.put(nums[i],i);
11         }
12         return false;
13     }
14 }

 【二刷】二刷和一刷的变动不是很大,但是对HashMap的了解更深了。

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         if(nums.length <= 1 || k == 0) return false;
 4         
 5         Map<Integer, Integer> map = new HashMap<>();
 6         for(int i = 0; i < nums.length; i++) {
 7             if(map.containsKey(nums[i]) && i-map.get(nums[i]) <= k)
 8                 return true;
 9             else map.put(nums[i], i);
10         }
11         return false;
12     }
13 }

【三刷】三刷的直接使用HashSet。遍历数组,如果当前下标已经大于k,则把set中不可能成立的数据删除掉,然后在把当前数字添加进去。如果set中已经包含该数,则会添加失败。

HashSet的add函数在添加成功返回true,在添加失败时返回false。

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         Set<Integer> set = new HashSet<Integer>();
 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 }
原文地址:https://www.cnblogs.com/liujinhong/p/5378481.html