AI智能
改变未来

LeetCode 220. Contains Duplicate III

可以用TreeSet来解决问题,但是为了防止溢出的问题,必须将类型强制转化成long(对应的包装类为Long)。

人工智能/ Solution {public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {// Corner caseif(nums == null || nums.length == 0){return false;}TreeSet<Long> set = new TreeSet<>();// Sliding windowfor(int i = 0; i < nums.length; i++){// Remove the element of which the distance is larger than kif(i > k){set.remove((long) nums[i – k – 1]);}// Get the least element which is larger than or equal to the given numberLong ceiling = set.ceiling((long) nums[i] – t);// Be cautious of the condition in which the return value is nullif(ceiling != null && ceiling <= (long) nums[i] + t){return true;}// Add the curren element into the setset.add((long) nums[i]);}return false;}}

 

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » LeetCode 220. Contains Duplicate III