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;
        }
    };
    

      

  • 相关阅读:
    leetcode——91.解码方法
    leetcode——64.最小路径和
    Layui上传图片2.0版
    LINQ中判断日期时间段
    Http基础
    Js中数组,字符串的常用方法
    C#数组,ArrayList,List区别
    08-01 通过线性回归了解算法流程
    08-00 课程习得
    C-02 推荐系统
  • 原文地址:https://www.cnblogs.com/hejunlin1992/p/7555090.html
Copyright © 2011-2022 走看看