Contains Duplicate III

Source: Internet
Author: User

Given an array of integers, find out whether there is II distinct indices i and J in the array such th At the difference between nums[i] and Nums[j] are at most T and the difference between I and J I S at the most K.

ref:http://bookshadow.com/weblog/2015/06/03/leetcode-contains-duplicate-iii/

That's a good thing. "Sliding window" procedure here

, newly learned a structure treeset

The following references the explanation of images "

Solution II: "Sliding window" + TreeSet

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

The TreeSet data structure (JAVA) is implemented using red-black trees and is a balanced binary tree.

The data structure supports the following operations:

1. Floor () method returns the largest element in the set that ≤ the given element, or null if no such element exists.

2. The ceiling () method returns the smallest element in the set ≥ the given element, or null if no such element exists.

There's an easy eight-brother place.

N<=t+set.floor (n))

Can not be written n-t "= ...

 Public classSolution { Public BooleanContainsnearbyalmostduplicate (int[] Nums,intKintt) {if(k<1| | T&LT;0)return false; TreeSet<Integer> set =NewTreeset<integer>();  for(inti=0;i<nums.length;i++){            intn =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; }}

Contains Duplicate III

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.