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

    【分析】

      1. 一直在想用HashMap解决问题,没办法。用了TreeSet(实现了SortedSet接口),SortedSet有个subSet(from, to)方法比较有效

      2. 主要需要比较坐标和元素值,使Set里最多只有k个元素,每加入一个元素,判断是否有两个元素的元素值之差小于t

    【算法实现】

    public boolean solution(int[] nums, int k, int t) {
        boolean b = false;
        TreeSet<Long> s = new TreeSet<Long>();
        for(int i=0; i<nums.length; i++) {
            TreeSet<Long> sub  = (TreeSet)s.subSet(nums[i]-t, true, nums[i]+t, true);
            if(!sub.isEmpty()) 
                return true;
            if(i >= k) {
                s.remove((long)nums[i-k]);
            }
            s.add((long)nums[i]);
        }  
        return false;
    }
  • 相关阅读:
    python内置模块collections介绍
    Python的set集合详解
    不同 Python 数据类型的搜寻
    Python 分支、循环、条件与枚举
    ssrf爆破mysql
    php反序列化
    thinkphp历史漏洞
    Thinkphp 缓存RCE
    绕WAF文章收集
    mssql手工盲注
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4550121.html
Copyright © 2011-2022 走看看