标签:
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
思路:这里需要注意两个地方,一是at most k 而是时间复杂度是O(n^2)时会TLE
代码:自己首先想到的是双重循环,时间复杂度O(n^2),结果肯定就是TLE
public boolean containsNearbyDuplicate(int[] nums, int k) { int i=0,j=1; while(i<nums.length) { j=1; while(i+j<nums.length && j<=k && nums[i]!=nums[i+j]) { j++; } if(i+j<nums.length && nums[i]==nums[i+j]) return true; i++; } return false; }
明显,题目要求时间复杂度更低的算法,比如O(n)
像这样的在临近找数值的题目,一般采用哈希表或者哈希集合去实现一个窗口。
在本题中采用哈希集合去实现一个长度为K的窗口,end不断向前走,当碰到end-start>k时,就remove掉nums[start],并且移动start。在K步中碰到相同的数,就返回true
实质就是,将前面的至多K个数存在哈希set里面,然后去找是否存在。时间复杂度O(n)
public boolean containsNearbyDuplicate(int[] nums, int k) { Set<Integer> set=new HashSet<Integer>(); int start=0,end =0; for(int i=0;i<nums.length;i++) { if(!set.contains(nums[i])) { set.add(nums[i]); end++; } else return true; if(end-start>k) { set.remove(nums[start]); start++; } } return false; }
优化:
扩展:
1、Given an array of integers and an integer k, return true if and only if 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.
上面那个题是存在,这个题是存在且只存在一组
2、Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
[LeetCode] Contains Duplicate II
标签:
原文地址:http://www.cnblogs.com/maydow/p/4642140.html