題目
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。
思路
題目本質是求,在不同位置是否存在相等的數。然後又加了一個限制條件,是否位置距離小於等於k。等於多加一個判斷即可。
代碼
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
//本質還是找相同的數,但是需要知道位置,然後計算i,j之差不大於k
map<int,int> dup_pos;
int hasDup = false;
for(int i = 0; i < nums.size(); ++i){
//之前已經出現了一次的。
if(dup_pos.count(nums[i]) > 0){
//計算是否小於等於k
//cout << dup_pos[nums[i]] <<endl;
if(i - dup_pos[nums[i]] <= k){
return true;
}
}
dup_pos[nums[i]] = i;
}
return false;
}
};