leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java
Posted xiaoba1203
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java相关的知识,希望对你有一定的参考价值。
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.
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的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode]220. Contains Duplicate III
[LeetCode] 220. Contains Duplicate III Java
Leetcode 220. 存在重复元素 III (Contains Duplicate III)
leetcode 220. Contains Duplicate III 求一个数组中有没有要求的元素 ---------- java