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;
    }
  • 相关阅读:
    P4568 [JLOI2011]飞行路线 最短路+分层图
    虚树
    点分治
    P2157 [SDOI2009]学校食堂 状压DP
    P2767 树的数量 DP | 组合数学
    CF348D LGV引理
    LGV引理
    P3647 [APIO2014]连珠线 换根DP
    第3章 决策树
    USDT/BTC/ETC/HT的解释
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4550121.html
Copyright © 2011-2022 走看看