码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java

时间:2017-04-24 12:27:08      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:ret   排序   span   tween   i++   lis   ash   content   情况   

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.

 

找出数组中有没有最多相距k,同时最大相差t的两个数。
 
1、第一次超时,用了很笨的办法,放入ArrayList中,但是由于特殊点,要用Long类型,然后每一次都需要排序,所以果断超时了。
public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (t < 0 || k < 1){
            return false;
        }
        if (k > nums.length - 1){
            k = nums.length - 1;
        }
        ArrayList<Long> list = new ArrayList();
        for (int i = 0; i <= k; i++){
            list.add((long)nums[i]);
        }
        Collections.sort(list);
        for (int i = 1; i < list.size(); i++){
            if (list.get(i) - list.get(i - 1) <= t){
                return true;
            }
        }
        for (int i = k + 1; i < nums.length; i++){
            list.remove((long)nums[i - k - 1]);
            list.add((long)nums[i]);
            Collections.sort(list);
            for (int j = 1; j < list.size(); j++){
                if (list.get(j) - list.get(j - 1) <= t){
                    return true;
                }
            }
        }
        return false;
    }
}

 

2、用map实现,类似于桶排序的原理,首先把数据都转成正数,并且使用long型(否则会出错,比如-2和2除以3都等于0,但是相距4大于3),同时桶(t) = t + 1(t == 0的情况要排出)

public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (k < 1 || t < 0){
            return false;
        }
        HashMap<Long, Long> map = new HashMap();
        for (int i = 0; i < nums.length; i++){
            
            long pos = (long) nums[i] - Integer.MIN_VALUE;
            long num = pos / ((long) t + 1);
            if (map.containsKey(num) || (map.containsKey(num - 1) && Math.abs(map.get(num - 1) - pos) <= t) 
                                     || (map.containsKey(num + 1) && Math.abs(map.get(num + 1) - pos) <= t)){
                return true;
            }
            if (map.size() >= k){
                long delete = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1);
                map.remove(delete);
            }
            map.put(num, pos);
        }
        return false;
    }
}

 

 

 

leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java

标签:ret   排序   span   tween   i++   lis   ash   content   情况   

原文地址:http://www.cnblogs.com/xiaoba1203/p/6739411.html

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