zoukankan      html  css  js  c++  java
  • Leetcode220. Contains Duplicate III存在重复元素3

    给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。

    示例 1:

    输入: nums = [1,2,3,1], k = 3, t = 0 输出: true

    示例 2:

    输入: nums = [1,0,1,1], k = 1, t = 2 输出: true

    示例 3:

    输入: nums = [1,5,9,1,5,9], k = 2, t = 3 输出: false

    方法一:暴力

    方法二:

    因为c++的map和set都是用搜索二叉树建立的

    所以可以用map或者set

    class Solution {
    public:
        bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) 
        {
            set<long long> s;
            for(int i = 0; i < nums.size(); i++)
            {
                set<long long> :: iterator itr = s.lower_bound((long long)nums[i] - t);
                if(itr != s.end() && abs((long long)nums[i] - *itr) <= t)
                {
                    return true;
                }
                s.insert(nums[i]);
                if(s.size() > k)
                    s.erase(nums[i - k]);
            }
            return false;
        }
    };
    

  • 相关阅读:
    mysql find_int_set
    PHPSTROM8.0 注册码(7.1也可用)
    gym 101657 D
    gym101657 C
    poj 3525
    poj1279
    poj3335
    poj 1228
    poj 1873
    poj 2074
  • 原文地址:https://www.cnblogs.com/lMonster81/p/10433814.html
Copyright © 2011-2022 走看看