[Leetcode] [Java] Contains Duplicate III

Source: Internet
Author: User

Contains Duplicate III

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.

There are two elements in the array, their value is less than or equal to T, and the subscript is less than or equal to K.

JavaScript time is very loose, violence O (n^2) directly can be past, but this question should be hope we use binary search tree.

K can be seen as a sliding window, for a new number, can be imagined to be placed on the left or right of the window, if the number +t or-t after falling in the window, directly return true.

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

Java BST:

1  Public classSolution {2      Public BooleanContainsnearbyalmostduplicate (int[] Nums,intKintt) {3Treeset<integer> TreeSet =NewTreeset<integer>();4          for(inti = 0; i < nums.length; i++){5Integer floor = Treeset.floor (Nums[i] +t);6Integer 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]);Ten             if(Treeset.size () > K) treeset.remove (Nums[i-K]); One         } A         return false; -     } -}

Brute Force:

1 /**2 * @param {number[]} nums3 * @param {number} K4 * @param {number} t5 * @return {Boolean}6  */7 varContainsnearbyalmostduplicate =function(Nums, K, t) {8      for(vari = 0; i < nums.length; i++)9          for(varj = i + 1; J < Nums.length; J + +)Ten             if(Math.Abs (Nums[i]-nums[j]) <= t && math.abs (I-J) <=k) One                 return true; A     return false; -};

[Leetcode] [Java] Contains Duplicate III

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.