zoukankan      html  css  js  c++  java
  • LeetCode:Contains Duplicate Ⅲ

    problems:

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

    解题思路:

        每访问一个数,把已经访问过的符合条件k的加入multiset中,同时要查看是否有符合条件t的  时间复杂度o(n)

    class Solution {
    public:
        bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
           
           multiset<int> set;
           for(int i=0;i<nums.size();i++)
           {
           if(set.size()==k+1)
           {
               set.erase(set.find(nums[i-k-1]));   
           }
           
           auto it=set.lower_bound(nums[i]-t);     //这儿不能用abs(nums[i]) 涉及到负数case 无法通过 [-1 -1] 2 0
          
           if(it!=set.end())
           {
                int gap = abs(nums[i]-*it);
                if(gap<=t)
                   return true;
           }       
           set.insert(nums[i]);
           }
           return false;
            
        }
    };

  • 相关阅读:
    nodejs + mongodb
    实习踩坑
    jQuery获取点击对象的父级
    python正则表达式
    python文件基础IO,OS
    python模块
    python时间和日期
    python number
    python循环
    Vue2.0 【第一季】第6节 v-model指令
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4561029.html
Copyright © 2011-2022 走看看