219. 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,找出数组中是否存在两个距离不超过k的相同的数。存在返回true;反之,返回false.
思路:我们首先想到的是将数组中的每个元素与它周围距离在k以内的元素对比,这样算法的时间复杂度为O(n2),算法效率太差。如果用set存放每次需要对比的数,那么每次查找的次数从k减少为logk,这样会大大提高效率。
代码如下:
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int>& nums, int k) { 4 set<int> s; 5 if(k <= 0) 6 { 7 return false; 8 } 9 if(k >= nums.size()) 10 { 11 k = nums.size() - 1; 12 } 13 for( int i = 0; i < nums.size(); i++ ) 14 { 15 if( i > k ) 16 { 17 s.erase(nums[i - k - 1]); 18 } 19 if( s.find(nums[i]) != s.end()) 20 { 21 return true; 22 } 23 s.insert(nums[i]); 24 } 25 return false; 26 } 27 };