Leetcode220——Contains Duplicate II

来源:互联网 发布:江南大学网络教育平台 编辑:程序博客网 时间:2024/06/03 17:17

很容易可以想到用一个窗口[i , i+k],然后再在窗口内find,用mutiset这样对某个数的find的时间复杂度O(logN),这样循环之后复杂度为(NlogN),主要注意事项是不能用set,需要用到multiset,然后此处不能直接用find(可能find不到),用lower_bound去find就可以了


很简单,直接上代码了

class Solution {public:    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {        int n = (int)nums.size();        if(n <= 1) return false;        multiset<long> st;                for(int i = 0; i<n; i++){            if(i-k-1 >= 0) st.erase(nums[i-k-1]);            auto fi = st.lower_bound((long)nums[i] - t);            if(fi != st.end() && *fi - nums[i] <= t) return true;            st.insert((long)nums[i]);        }        return false;    }}    

lz是智障,这里把insert操作写在老前面了,于是每次都是return true(自己减自己sad),蠢爆炸了。


lz是智障,这题分类是bst,于是lz用bst做了做,还是老思路,先查询并判断,然后插入,两步走,注定会超时。

struct node{        node* l, *r;        int num;        int index;        node(int num, int index): num(num), index(index), l(NULL), r(NULL) {}    };        bool Find(node* root, int num, int index, int k, int t){        if(root == NULL) return false;        if(index - root->index > k) return (Find(root->r, num, index, k, t) || Find(root->l, num, index, k, t));        else{            if(num - root->num <= t && num - root->num >= -t) return true;            else if(num - root->num > t) return Find(root->r, num, index, k, t);            else return Find(root->l, num, index, k, t);        }    }        void Insert(node* &root, int num, int index){        if(root == NULL) {root = new node(num, index); return;}        if(num < root->num) Insert(root->l, num, index);        else Insert(root->r, num, index);    }        bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {        int n = (int)nums.size();        node *root = NULL;        for(int i = 0; i<n; i++){            if(Find(root, nums[i], i, k, t)) return true;            else Insert(root, nums[i], i);        }        return false;    }



原创粉丝点击