(Medium) Leetcode 220.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.

Thought for reference: maintain a window of length k, each time checking whether the new value is less than or equal to the value of all values in the original window. If the two for loop will time out O (NK). You can quickly search by using the subset function of TreeSet (backed by binary search tree). Complexity of O (n logk)

The code is as follows:

Import Java.util.sortedset;public class Solution {public    Boolean containsnearbyalmostduplicate (int[] nums, int k, int T) {        if (k<1 | | t<0 | | Nums==null | | NUMS.LENGTH<2) return false;        Sortedset<long>set=new treeset<> ();        int len=nums.length;        for (int i=0;i<len;i++) {            sortedset<long>subset=set.subset (long) nums[i]-t, (long) nums[i]+t+1);            if (!subset.isempty ()) return true;            if (i>=k)               Set.remove ((long) nums[i-k]);            Set.add ((long) nums[i]);           }        return false;    }}

Operation Result:

(Medium) Leetcode 220.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.