zoukankan      html  css  js  c++  java
  • [LeetCode] 220. Contains Duplicate III 包含重复元素 III

    Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

    Example 1:

    Input: nums = [1,2,3,1], k = 3, t = 0
    Output: true
    

    Example 2:

    Input: nums = [1,0,1,1], k = 1, t = 2
    Output: true
    

    Example 3:

    Input: nums = [1,5,9,1,5,9], k = 2, t = 3
    Output: false

    给定一个数组和两个整数t 和k ,求是否有不同的两个下标i和j,满足|nums[i] – nums[j]|<= t && | i – j | <=k

    解法:参考: 细语呢喃

    Java:

    class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if (k <= 0 || t < 0) return false;
            TreeSet<Long> tree = new TreeSet<>();
            for (int i = 0; i < nums.length; i++) {
                Long x = tree.ceiling((long) nums[i] - t);
                if (x != null && x <= (long) nums[i] + t) return true;
                if (i >= k)
                    tree.remove((long) nums[i - k]);
                tree.add((long) nums[i]);
            }
            return false;
        }
    }  

    Python:

    class Solution:
        # @param {integer[]} nums
        # @param {integer} k
        # @param {integer} t
        # @return {boolean}
        def containsNearbyAlmostDuplicate(self, nums, k, t):
            if k < 0 or t < 0:
                return False
            window = collections.OrderedDict()
            for n in nums:
                # Make sure window size
                if len(window) > k:
                    window.popitem(False)
                    
                bucket = n if not t else n // t
                # At most 2t items.
                for m in (window.get(bucket - 1), window.get(bucket), window.get(bucket + 1)):
                    if m is not None and abs(n - m) <= t:
                        return True
                window[bucket] = n
            return False 

    C++:

    class Solution {
    public:
        bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
            map<long long, int> m;
            int j = 0;
            for (int i = 0; i < nums.size(); ++i) {
                if (i - j > k) m.erase(nums[j++]);
                auto a = m.lower_bound((long long)nums[i] - t);
                if (a != m.end() && abs(a->first - nums[i]) <= t) return true;
                m[nums[i]] = i;
            }
            return false;
        }
    };
    

      

    类似题目:

    [LeetCode] 217. Contains Duplicate 包含重复元素

    [LeetCode] 219. Contains Duplicate II 包含重复元素 II

      

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    寒假学习进度8
    寒假学习进度7
    寒假学习进度6
    寒假学习进度5
    寒假学习进度4
    寒假学习进度3
    寒假自学进度13
    Python引用某一文件的方法出现红色波浪线
    寒假自学进度11
    正则表达式(学习)
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8648512.html
Copyright © 2011-2022 走看看