您的位置:首页 > 大数据 > 人工智能

220. Contains Duplicate III—medium

2016-07-26 23:20 603 查看
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] andnums[j] is at most t and the difference between i and j is at most k.

题目解释:并不是要求所有,只要有一组满足即可

暴力法:(超时)

class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (nums.size() <= 1 || k == 0)
return false;

vector<long int> numDiff;
vector<long int> sumVec(nums.size());
sumVec[0] = 0;
for (int i = 0; i < nums.size() - 1; i ++){
numDiff.push_back(nums[i+1] - nums[i]);     //nums[j] - nums[i] = numDiff[i] + numDiff[i+1] + ... + numDiff[j-1]
}

for(int i = 0; i < nums.size(); i ++){
for (int len = 1; len <= k && i + len < nums.size(); len ++){
sumVec[len] = sumVec[len - 1] + numDiff[i+len-1];
if(abs(sumVec[len]) <= t)
return true;
}
}

return false;
}
};


下面的借鉴的一种,最差复杂度也是O(N^2),但是出现最差情况的几率很小

class Solution {
public:
static bool lessthan(pair<int, int> a, pair<int, int> b){
return a.first < b.first;
}
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
vector<pair<int, int> > a;
for (int i = 0; i < nums.size(); i ++){
a.push_back(make_pair(nums[i], i));
}
sort(a.begin(), a.end(), lessthan);
int big = 0, small = 0;
for(int big = 1; big < nums.size(); big ++){
while((long)a[big].first - a[small].first > t) small ++;
for(int j = small; j < big; j ++){
if (abs(a[big].second - a[j].second) <= k){
return true;
}
}
}
return false;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: