Description:
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array
Note:
such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
Solution:
Analysis and Thinking:
題目要求給出一個整數數組的情況下,判斷該數組內是否有相等的元素值,要求索引相差不大於K,依據題意,藉助map的結構就可完成
Steps:
1. 定義一個map,用於記錄當前關鍵字和下標值
2. 遍歷數組,用map統計當前元素在map中的出現個數,如果不爲0(證明已經出現過)且其記錄的value即該元素下標與當前下標相減的絕對值小於等於k,返回true
3. 如果出現次數爲0,將該元素以及對應下標添加入map中
Codes:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
if(nums.size()<=1) return false;
if(k<-0) return false;
map<int,int> record;
for(int i=0;i<nums.size();i++)
{
if(record.count(nums[i]) && abs(record[nums[i]]-i)<=k)
{
return true;
}
else
{
record[nums[i]] = i;
}
}
return false;
}
Results: