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.
Hide Tags Binary Search Tree分析:
此題和前一題的差別在於,需要同時判斷數組元素和對應下標是否滿足條件。還是藉助結構體,將數組元素和對應的下標存放到一個結構體數組中,然後對結構體數組進行一級排序,之後利用雙指針判斷是否存在值元素相差不大於t且對應下標相差不大於k。
實現時,在判斷值相差是否不大於t的時候,要注意防止整型溢出,所以應該將其變形爲等價的表達式,即判斷較小元素與t的和是否不小於於較大元素。
以下是C++實現代碼:
*///////////////////////////20ms///*/
struct Node{
int num; //數組元素
int index; //數組元素對應下標
};
int cmp(Node &a,Node &b) //結構體一級排序函數
{
return a.num < b.num;
}
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int size = nums.size();
if(k <= 0)
return false;
vector<Node> vec;
for(int i = 0; i != size; i++) //將nums中的元素放入一個結構體數組中
{
Node nod;
nod.num = nums[i];
nod.index = i;
vec.push_back(nod);
}
sort(vec.begin(),vec.end(),cmp); //非遞減排序
int i = 0, j = 1; //以下是雙指針查找,i,j分別爲左右指針
while( i < j && j != size )
{
if(vec[j].num <= t + vec[i].num) //防止整型溢出
{
if(abs(vec[j].index - vec[i].index)<=k) //找到滿足條件的數
return true;
j++;
if(i < j && j == size) //右指針已超出數組下標,表示數組的num是滿足條件的,但是下標不滿足,所以修改左右指針,繼續下一個循環
{
i++;
j = i+1;
}
}
else //數組元素就不滿足,直接將兩個指針同時右移一個位置
{
i++;
j = i+1;
}
}
return false;
}
};