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

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; 

    }

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