Middle-题目122:220. Contains Duplicate III

原创 2016年05月31日 20:13:20

题目原文:
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.
题目大意:
给出一个数组nums,判断是否存在这样两个下标i和j使得|nums[i]-nums[j]≤t,且|j-i|≤k.
题目分析:
巧用TreeSet这个类,它是一个集合,元素不可重复,不可维护加入集合的顺序,但集合是有序的,有floor(n)和ceiling(n)两个方法取得元素n相邻的两个元素。
那么构造一个TreeSet,并维持TreeSet的长度为K(如果i超过k就把nums[i-k]弹出去)。然后设n=nums[i].每次判断n-floor(n)是否≤t或者ceiling(n)是否≤t(因为TreeSet的长度不超过k,所以如果存在floor(n)或者ceiling(n),其在数组的下标与n的差值必然不超过k),若存在则找到解,返回true,若不存在则加入n,弹出nums[i-k],总的时间复杂度是O(nlogk) (因为TreeSet的add和remove都是logk复杂度的)
源码:(language:java)

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

成绩:
68ms,beats 10.72%,众数23ms,5.88%
Cmershen的碎碎念:
本题类似于滑动窗口,是第一道需要用到TreeSet的题,但是效率不高,可能有O(n)的线性算法。TreeSet基于红黑树实现,它遗失插入顺序但保证集合内有序,而红黑树是一种应用广泛的用于查找的二叉树,关于红黑树的详细了解可自行百度。类似的数据结构还有TreeMap(保证key有序)。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

Leetcode220-Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array suc...

220. Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array s...

217, 219,220. Contains Duplicate I, II, III

Given an array of integers, find if the array contains any duplicates. Your function should return ...

Contains Duplicate III - LeetCode 220

题目描述: Given an array of integers, find out whether there are two distinct indices i and j in the ar...

[leetcode ]220.Contains Duplicate III

题目: Given an array of integers, find out whether there are two distinct indices i and j in the arra...

【LEETCODE】220-Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array  ...

Leetcode 220. Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array suc...

[Leetcode 220, Medium] Contains Duplicates III

[Leetcode 220, Medium] Contains Duplicates III

[LeetCode]217. Contains Duplicate&219. Contains Duplicate II&220. Contains Duplicate III

217. Contains Duplicate 219. Contains Duplicate II 220. Contains Duplicate III

【leetcode题解】【再看一遍】【86】【M】Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array suc...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)