220. Contains Duplicate III
原题链接:https://leetcode.com/problems/contains-duplicate-iii/description/
这道题目不会做,别人的答案也没看懂。以后有钱了订阅会员看官方答案吧:
import java.util.HashMap;
import java.util.Map;
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
}
/**
* 这道题目我思考了半天都没想出答案来,官方的答案又得订阅会员才能看到。。无奈之下看了下讨论区别人的答案,发现确实思路灰常不错,脑洞大开
*
* 妈的,刚开始以为自己看懂了呢。其实看懂了个屁。。这个方法:beats 91.94 %
*
* @param nums
* @param k
* @param t
* @return
*/
public boolean containsNearbyAlmostDuplicate1(int[] nums, int k, int t) {
if (k < 1 || t < 0) {
return false;
}
Map<Long, Long> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
long remappedNum = (long) nums[i] - Integer.MIN_VALUE;
long bucket = remappedNum / ((long) t + 1);
if (map.containsKey(bucket)
|| (map.containsKey(bucket - 1) && remappedNum - map.get(bucket - 1) <= t)
|| (map.containsKey(bucket + 1) && map.get(bucket + 1) - remappedNum <= t)) {
return true;
}
if (map.entrySet().size() >= k) {
long lastBucket = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1);
map.remove(lastBucket);
}
map.put(bucket, remappedNum);
}
return false;
}
// 然后,我又看了下提交区效率最高的答案,马丹,就是最简单的暴力方法
// 奶奶的,不知道为啥我提交这个答案就是超时了。。。不玩了
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (k < 1 || t < 0 || nums.length <= 1) {
return false;
}
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length && (j - i) <= k; j++) {
if (Math.abs((long) nums[j] - nums[i]) <= t) {
return true;
}
}
}
return false;
}
}