zoukankan      html  css  js  c++  java
  • [LeetCode][Java]Contains Duplicate III

    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 difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.


    数组中是否存在两个元素,他们的值小于等于t,并且下标小于等于k。

    Javascript时间很宽松,暴力O(n^2)直接可以过,但这题应该是希望我们用二叉搜索树。

    可以把k看做滑动窗口,对于一个新的数,可以想象成放到这个窗口的最左边或者最右边,如果这个数+t或-t之后落在窗口里,直接返回true。

    https://leetcode.com/discuss/38177/java-o-n-lg-k-solution

    Java BST: 

     1 public class Solution {
     2     public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
     3         TreeSet<Integer> treeSet = new TreeSet<Integer>();
     4         for(int i = 0; i < nums.length; i++){
     5             Integer floor = treeSet.floor(nums[i] + t);
     6             Integer ceiling = treeSet.ceiling(nums[i] - t);
     7             if( (floor != null && floor >= nums[i]) 
     8                 || (ceiling != null && ceiling <= nums[i]) ) return true;
     9             treeSet.add(nums[i]);
    10             if(treeSet.size() > k) treeSet.remove(nums[i - k]);
    11         }
    12         return false;
    13     }
    14 }

    Brute Force:

     1 /**
     2  * @param {number[]} nums
     3  * @param {number} k
     4  * @param {number} t
     5  * @return {boolean}
     6  */
     7 var containsNearbyAlmostDuplicate = function(nums, k, t) {
     8     for(var i = 0; i < nums.length; i++)
     9         for(var j = i + 1; j < nums.length; j++)
    10             if(Math.abs(nums[i] - nums[j]) <= t && Math.abs(i - j) <= k)
    11                 return true;
    12     return false;
    13 };
  • 相关阅读:
    快速排序理论---不含源码
    归并排序理论---不含源码
    希尔排序(shell)理论---不含源码
    Visual C++中error spawning cl.exe解决办法
    数据库的基础知识点---1
    冒泡排序的基础知识部分(不含源码)
    在虚拟机的Linux系统下安装wineqq
    数据变量的别名
    void*和void类型
    变量的作用域和连接性
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5084305.html
Copyright © 2011-2022 走看看