码迷,mamicode.com
首页 > 其他好文 > 详细

220-Contains Duplicate III

时间:2015-06-03 21:24:54      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

【题目】

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

 

220-Contains Duplicate III

标签:

原文地址:http://www.cnblogs.com/hwu2014/p/4550121.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!