zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    PHP 数据库连接
    php函数
    php数组基础
    Jquery元素追加和删除
    jquery获取父,同,子级元素
    深入理解css中position属性及z-index属性
    php运算符
    MySQL主键与索引的区别和联系
    php 常量
    20150408--Sphinx+邮件激活-02
  • 原文地址:https://www.cnblogs.com/lailailai/p/4558166.html
Copyright © 2011-2022 走看看