• LeetCode Contains Duplicate III


    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.

    要是面试,那么我已经跪了

    class Solution {
    public:
        bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
            if (t < 0 || k <1) {
                return false;
            }
            long bucket_size = (long)t + 1;
            long len = nums.size();
            unordered_map<long, long> buckets;
            for (long i=0; i<len; i++) {
                long val = nums[i] - (long)INT_MIN;
                long bucket = val / bucket_size;
                // check duplicates in buckets[bucket-1], buckets[bucket], buckets[bucket+1]
                if (buckets.count(bucket) > 0 
                    || buckets.count(bucket-1) > 0 && val - buckets[bucket - 1] <= t
                    || buckets.count(bucket+1) > 0 && buckets[bucket + 1] - val <= t) {
                    return true;        
                }
                // maintain buckets entries in a k size window (the index constrains)
                if (buckets.size() >= k) {
                    int bucket2del = (nums[i - k] - (long)INT_MIN) / bucket_size;
                    buckets.erase(bucket2del);
                }
                buckets[bucket] = val;
            }
            return false;
        }
    };

     用set不靠谱啊,这个提示binary search tree难道不是这么用,直接TLE了:

    class Solution {
    public:
        bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
            if (t < 0 || k <1) {
                return false;
            }
            int len = nums.size();
            set<long> win;
            
            for (int i=0; i<len; i++) {
                long val = nums[i];
                auto lo = lower_bound(win.begin(), win.end(), val - t);
                if (lo != win.end()) {
                    if (abs(*lo - val) <= t) {
                        return true;
                    } else {
                        // not found
                    }
                }
                // sliding window
                if (i >= k) {
                    win.erase(nums[i - k]);
                }
                win.insert(val);
            }
            
            return false;
        }
    };
  • 相关阅读:
    django channels 模型图
    React-Router 非Route监管组件如何监听location变化?
    djoser
    Integration of hot-load django dev sever and hot-load reactjs dev server
    type annotation / static checker / dynamic checker of python
    Prototype of Draw and Guess Game
    Django Channels -- more than HTTP
    DRF Views Inheritance Relationships
    Django REST framework -- ViewSets & Routers
    Django REST framework -- Relationships & Hyperlinked APIs
  • 原文地址:https://www.cnblogs.com/lailailai/p/4558166.html
Copyright © 2020-2023  润新知