contains duplicate 3
2016-05-09 15:38
447 查看
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.
直观解法:两重循环,维护一个k大小的窗口,时间复杂度是O(N^2),必然无法通过所有测试数据。
class Solution
{
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int m=nums.size();
if (m==0 || m==1)
return false;
if(k<1||t<0){
return false;
}
for (int i=0;i<m;i++){
int j;
j=i+1;
for (j;j<=i+k;j++){
if (abs(nums[i]-nums[j])<=t)
return true;
}
}
return false;
}
};
优先选择的数据结构:二叉树。时间复杂度O(N*log(N))。
class
Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long long> tree;
for(int i = 0; i< nums.size(); i++)
{
//cout<<"nums["<<i<<"]:"<<nums[i]<<endl;
if(tree.size() > k)
tree.erase(nums[i-k-1]); //只维护一个长度为k的树
auto p = tree.lower_bound(nums[i]-t); //找到一个不小于nums[i]的值
if (p != tree.end() && *p - nums[i] <= t) //与nums[i]比较 如果符合要求返回真
//{
//cout <<"lower bound:"<< *p<<endl;
return true;
//}
tree.insert(nums[i]);
}
return false;
}
};
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.
直观解法:两重循环,维护一个k大小的窗口,时间复杂度是O(N^2),必然无法通过所有测试数据。
class Solution
{
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
int m=nums.size();
if (m==0 || m==1)
return false;
if(k<1||t<0){
return false;
}
for (int i=0;i<m;i++){
int j;
j=i+1;
for (j;j<=i+k;j++){
if (abs(nums[i]-nums[j])<=t)
return true;
}
}
return false;
}
};
优先选择的数据结构:二叉树。时间复杂度O(N*log(N))。
class
Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long long> tree;
for(int i = 0; i< nums.size(); i++)
{
//cout<<"nums["<<i<<"]:"<<nums[i]<<endl;
if(tree.size() > k)
tree.erase(nums[i-k-1]); //只维护一个长度为k的树
auto p = tree.lower_bound(nums[i]-t); //找到一个不小于nums[i]的值
if (p != tree.end() && *p - nums[i] <= t) //与nums[i]比较 如果符合要求返回真
//{
//cout <<"lower bound:"<< *p<<endl;
return true;
//}
tree.insert(nums[i]);
}
return false;
}
};
相关文章推荐
- MIT Introduction to Algorithms 学习笔记(六)
- Binary Search Tree Iterator,Reverse Nodes in k-Group
- [LeetCode] Convert Sorted List to Binary Search Tree
- [LeetCode] Convert Sorted Array to Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Unique Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- LeetCode:Binary Search Tree相关题目合集
- LeetCode-Convert Sorted Array to Binary Search Tree
- Convert Sorted Array(List) to Binary Search Tree
- Validate Binary Search Tree
- convert sorted array to binary search tree
- Binary Tree Inorder Traversal
- Binary Search Tree Iterator
- Binary Tree Postorder Traversal
- Kth Smallest Element in a BST
- [Leetcode]Recover Binary Search Tree
- [Leetcode]Validate Binary Search Tree
- [Leetcode]Unique Binary Search Trees II