leet-code/src/main/java/leetcode/editor/cn/ContainsDuplicateIii.java
2021-04-29 23:21:52 +08:00

71 lines
1.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给你一个整数数组 nums 和两个整数 k 和 t 。请你判断是否存在 两个不同下标 i 和 j使得 abs(nums[i] - nums[j]) <=
//t ,同时又满足 abs(i - j) <= k 。
//
// 如果存在则返回 true不存在返回 false。
//
//
//
// 示例 1
//
//
//输入nums = [1,2,3,1], k = 3, t = 0
//输出true
//
// 示例 2
//
//
//输入nums = [1,0,1,1], k = 1, t = 2
//输出true
//
// 示例 3
//
//
//输入nums = [1,5,9,1,5,9], k = 2, t = 3
//输出false
//
//
//
// 提示:
//
//
// 0 <= nums.length <= 2 * 104
// -231 <= nums[i] <= 231 - 1
// 0 <= k <= 104
// 0 <= t <= 231 - 1
//
// Related Topics 排序 Ordered Map
// 👍 391 👎 0
package leetcode.editor.cn;
import java.util.*;
//220:存在重复元素 III
public class ContainsDuplicateIii {
public static void main(String[] args) {
//测试代码
Solution solution = new ContainsDuplicateIii().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
int n = nums.length;
TreeSet<Long> set = new TreeSet<>();
for (int i = 0; i < n; i++) {
Long ceiling = set.ceiling((long) nums[i] - (long) t);
if (ceiling != null && ceiling <= (long) nums[i] + (long) t) {
return true;
}
set.add((long) nums[i]);
if (i >= k) {
set.remove((long) nums[i - k]);
}
}
return false;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}