zoukankan      html  css  js  c++  java
  • [Leetcode] 220. 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 absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

      题目大意:给定一个整数数组nums,找出是否存在:两个不同的下标(索引index)i 和 j ,使得nums[i] 和 nums[j]的差的绝对值小于等于t,i 和 j 的差的绝对值小于等于k。

      思路:建立一个set数据类型,把 i 之前k个数存入set中,set默认数据是从小到大排序的。

         对于i,j 时,若符合条件,则有 | nums[j] - nums[i] |<=t,则-t <= nums[j] - nums[i] <= t,因此有nums[j]>=num[i] - t,因此使用lower_bound函数获取set中大于等于num[i] - t的第一个元素,若存在该元素(it!=s.end()),则再判断 nums[j] - nums[i] <= t是否成立,需要注意的是整数可能溢出

    class Solution {
    public:
        bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
            set<int> s;
            for(int i=0;i<nums.size();i++)
            {
                //if(s.size()==k) s.erase(nums[i-k]);//错误!
                if(i-k-1>=0) s.erase(nums[i-k-1]);//当i>k+1时,就一直删除最先存入set里面的数
    
                auto it = s.lower_bound(nums[i]-t);
                if(it!=s.end()&&((long)*it-(long)nums[i])<=t) return true;
                s.insert(nums[i]);
            }
            return false;
        }
    };
    

      

  • 相关阅读:
    SDUST OJ 时间类的加、减法赋值运算
    POJ 2823 (滑动窗口)
    POJ 2229 计数DP
    POJ 1995 (快速幂)
    poj 3009 (深搜求最短路)
    C++ 学习笔记之 STL 队列
    C++ 学习笔记之 引用
    Anaconda3使用
    Ubuntu 18.04安装Conda、Jupyter Notebook、Anaconda
    Ubuntu 18.04安装 pyenv、pyenv-virtualenv、virtualenv、Numpy、SciPy、Pillow、Matplotlib
  • 原文地址:https://www.cnblogs.com/hejunlin1992/p/7555090.html
Copyright © 2011-2022 走看看