• LeetCode——Contains Duplicate III


    Description:

    Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

    题目大意:给定一个数组,和两个数t和k。判断是否满足下列条件的数。存在两个不同的下标i,j满足: nums[i] - nums[j] | <= t 且 | i - j | <= k。

    思路:使用Java中的TreeSet,TreeSet是有序的内部是红黑树实现的。并且内部带有操作方法很方便,会降低问题的复杂度。其实就是一个滑动窗口,把可能满足条件的范围从左向右滑动,直到找出满足条件的数或者窗口滑动完毕。

    实现代码:

    public class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            
            if(k < 1 || t < 0) return false;
            
            TreeSet<Integer> set = new TreeSet<Integer>();
            
            for(int i=0; i<nums.length; i++) {
                int cur = nums[i];
                Integer floor = set.floor(cur);
                Integer ceil = set.ceiling(cur);
                
                if(floor != null && cur <= t + floor
                    || ceil != null && ceil <= t + cur) {
                    return true;
                }
                set.add(cur);
                if(i >= k) {
                    set.remove(nums[i - k]);
                }
            }
            return false;
        }
    }

  • 相关阅读:
    Python ---chart
    python ---Pandas时间序列:生成指定范围的日期
    python 生成图表
    top 学习
    linux awk命令详解
    /proc 目录详细说明
    ps 和 top 的cpu的区别
    linux 监控性能学习笔记(1)
    转如何用九条命令在一分钟内检查Linux服务器性能?
    Linux系统排查——CPU负载篇
  • 原文地址:https://www.cnblogs.com/wxisme/p/4934371.html
Copyright © 2020-2023  润新知