博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
220. Contains Duplicate III
阅读量:7038 次
发布时间:2019-06-28

本文共 2269 字,大约阅读时间需要 7 分钟。

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.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3Output: false

难度:medium

题目:给定一整数数组,找出是否存在两个不同的索引i, j使其索引差的绝对值小于等于k, 值的差的绝对值小于等于t.

思路:

  1. 暴力破解,
  2. 使用滑动窗口和TreeSet是为了使得滑动窗口有序,TreeSet底层是二叉搜索树, 如果暴力破解时间复杂度为O(kn), 改用TreeSet使得搜索时间复杂度为O(log K), 故总的时间复杂度为O(nlog K)。

Runtime: 22 ms, faster than 70.38% of Java online submissions for Contains Duplicate III.

Memory Usage: 40.4 MB, less than 5.58% of Java online submissions for Contains Duplicate III.

class Solution {    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {        if(nums == null || nums.length < 2 || k < 1 || t < 0){            return false;        }        TreeSet
treeSet = new TreeSet<>(); for (int i = 0; i < nums.length; i++) { if (!treeSet.subSet((long) nums[i] - t, true, (long) nums[i] + t, true).isEmpty()) { return true; } if (i >= k) { treeSet.remove((long) nums[i - k]); } treeSet.add((long) nums[i]); } return false; }}

Runtime: 987 ms, faster than 5.06% of Java online submissions for Contains Duplicate III.

Memory Usage: 38.8 MB, less than 56.75% of Java online submissions for Contains Duplicate III.

class Solution {    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {        for (int i = 0; i < nums.length; i++) {            for (int j = i + 1; j < Math.min(nums.length, i + k + 1); j++) {                if (nums[i] > 0 && nums[j] < 0 || nums[i] < 0 && nums[j] > 0) {                    if (Math.abs(nums[i]) - t > 0                         || Math.abs(nums[i]) - t + Math.abs(nums[j]) > 0) {                        continue;                    }                }                                if (Math.abs(nums[i] - nums[j]) <= t) {                    return true;                }            }        }                            return false;    }}

转载地址:http://renal.baihongyu.com/

你可能感兴趣的文章
中小企业是否需要邮件服务器系统
查看>>
关机命令
查看>>
禁止浏览器缓存的响应头和定时刷新
查看>>
Win8.1下安装Sass Compass
查看>>
sjtu oj 1250 最大连续子序列问题变形
查看>>
OSPF在企业网络中的应用
查看>>
运维核心之一 CMDB
查看>>
python高性能编程--002--全局解释器锁GIL
查看>>
VSS 信息安全
查看>>
python基础学习笔记
查看>>
Java的HashMap和HashTable
查看>>
我的友情链接
查看>>
windows系统之WSUS服务器:更改WSUS更新文件的路径
查看>>
Btrace
查看>>
我的友情链接
查看>>
python抓取豆瓣妹子图片并上传到七牛
查看>>
关于Spring Data redis几种对象序列化的比较
查看>>
windows下批处理设置U盘盘符为U【非PE】
查看>>
Windows系统补丁KB2962872导致InstallShield无法启动(解决方案已更新)
查看>>
#每天问自己个问题#0. 每天问自己个问题
查看>>