zoukankan      html  css  js  c++  java
  • Contains Duplicate III —— LeetCode

    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,下标i和j相差<=k。

    解题思路:题目没说数组有序,那就得按照无序处理,可以排序,然后从头遍历;或者用个BST之类的有序数据结构,遍历数组的时候重建一下,重建的过程中判断是否有合法的解,有就返回true,否则重建完之后返回false。

    public class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            if(nums==null||nums.length==0||k<=0){
                return false;
            }
            TreeSet<Integer> tree = new TreeSet<>();
            for(int i=0;i<nums.length;i++){
                Integer big = tree.floor(nums[i]+t);//floor返回集合里<=指定元素的最大值
                Integer small = tree.ceiling(nums[i]-t);//celing返回集合里>=指定元素的最小值
                if((big!=null&&big>=nums[i])||(small!=null&&small<=nums[i])){
                    return true;
                }
                if(i>=k){
                    tree.remove(nums[i-k]);
                }
                tree.add(nums[i]);
            }
            return false;
        }
    }
  • 相关阅读:
    传纸条
    金明的预算方案
    矩阵取数
    能量项链
    选择客栈
    过河
    乌龟棋
    逢低吸纳
    三角形牧场
    多米诺骨牌
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4600058.html
Copyright © 2011-2022 走看看