Leetcode 220. Contains Duplicate III

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/83348830

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Contains Duplicate III

2. Solution

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

Reference

  1. https://leetcode.com/problems/contains-duplicate-iii/description/
阅读更多

扫码向博主提问

SnailTyan

博客专家

非学,无以致疑;非问,无以广识
  • 擅长领域:
  • 深度学习
  • PyTorch
  • OCR
  • Docker
  • Caffe
去开通我的Chat快问
换一批

没有更多推荐了,返回首页