zoukankan      html  css  js  c++  java
  • 220. 存在重复元素 III

    在整数数组 nums 中,是否存在两个下标 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值小于等于 t ,且满足 i 和 j 的差的绝对值也小于等于 ķ 。

    如果存在则返回 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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/contains-duplicate-iii
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if(nums==null||nums.length<2||k<0||t<0)return false;
            TreeSet<Long>set=new TreeSet<Long>();
            for(int i=0;i<nums.length;i++){
                long cur=(long)nums[i];
                long left=cur-t;
                long right=cur+t+1;
                SortedSet<Long> sub=set.subSet(left,right);
                if(sub.size()>0){
                    return true;
                }
                set.add(cur);
                if(i>=k){
                    set.remove((long)nums[i-k]);
                }
            }
            return false;
        }
    }

    用floor(x) , ceiling(x)

    class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if (k < 1 || t < 0)
                return false;
            
            TreeSet<Long> set = new TreeSet<Long>();
        
            for (int i = 0; i < nums.length; i++) {
                long c = (long)nums[i];
                if ((set.floor(c) != null && c <= set.floor(c) + (long)t)
                || (set.ceiling(c) != null && c >= set.ceiling(c) -(long)t))
                    return true;
        
                set.add(c); 
        
                if (i >= k)
                    set.remove((long)(nums[i - k]));
            }
        
            return false;
        }
    }
  • 相关阅读:
    MongoDB 基本概念
    MongoDB 设置参数
    MongoDB 操作数据库
    MongoDB 目录分析、基础命令、参数设置
    Windows下MongoDB的下载安装、环境配置
    MongoDB 简介
    SQL与NoSQL
    es6 箭头函数(arrow function) 学习笔记
    WebPack 简明学习教程
    vue自定义指令
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13899034.html
Copyright © 2011-2022 走看看