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 };
  • 相关阅读:
    两个链表的第一个公共节点
    笔试题总结
    SMTP协议分析
    用两个栈实现一个队列
    医院Android项目总结
    C标准I/O库函数与Unbuffered I/O函数
    ELF文件
    x86汇编程序基础(AT&T语法)
    【转】Linux C动态内存泄漏追踪方法
    Minor【 PHP框架】6.代理
  • 原文地址:https://www.cnblogs.com/Liok3187/p/5084305.html
Copyright © 2011-2022 走看看