220. Contains Duplicate III
阿新 • • 發佈:2018-03-23
-i hashmap map remove ati iii boolean set static
原題鏈接: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;
}
}
220. Contains Duplicate III