zoukankan      html  css  js  c++  java
  • Leetcode 220. Contains Duplicate III

    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.

     
     
     
    思路:维持一个大小为k的窗口,由左向右在nums中移动。对于nums[i],只要查找其之前的元素中是否存在大小范围在[nums[i] - t,nums[i] + t]的元素,如果存在就返回true。还要注意整数的溢出问题,比如下面的测试用例:
    [0,2147483647]
    1
    2147483647
     
    代码:
     1 public class Solution {
     2     public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
     3         if (nums == null || nums.length == 0 || k <= 0)
     4             return false;
     5         TreeSet<Long> ts = new TreeSet();
     6         for (int i = 0; i < nums.length; ++i) {
     7             Long right = ts.floor((long) nums[i] + t);
     8             Long left = ts.ceiling((long) nums[i] - t);
     9             if (right != null && left != null && right >= left)
    10                 return true;
    11             ts.add((long) nums[i]);
    12             if (i >= k)//i >= k说明nums[i]之前至少已经有k各不相同的元素(否则早就返回true)
    13                 ts.remove((long) nums[i - k]);
    14 //             //将上面的if改写成以下条件也是正确
    15 //             if (ts.size() >= k)//
    16 //                 ts.remove((long) nums[i - k]);
    17 
    18         }
    19         return false;
    20     }
    21 }
  • 相关阅读:
    C++输入问题探究
    剑指offer自学系列(一)
    一道算法题加深我对C++中map函数的理解
    数据结构和算法自学之排序算法(一)
    pyqt5_01_流程走通
    最新谷歌驱动对照表
    移动端测试
    selenium封装
    request封装
    MD5自定义加密
  • 原文地址:https://www.cnblogs.com/Deribs4/p/6611329.html
Copyright © 2011-2022 走看看