"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 are at the most K.

Tips:

See the topic, immediately think of the topic should be to use a length of the window of k, then the problem is to use what data structure to construct the window. Since when the new number comes in, we need to compare it to the size of other numbers in the window, we can use BST from the point of view of the efficiency of the search, so we choose the Set container in STL to construct the window.

The idea is also very simple, when the new come in a number, first in the container to find whether there is larger than the number of nums[i]-t, this step can be achieved by using the Lower_bound function, and then compare the nums[i]-t larger than the number of the smallest and nums[i] difference, Returns true if the condition is met.

Also do not forget to delete and insert the corresponding element when the window is moved.

Code:
classSolution { Public:    BOOLContainsnearbyalmostduplicate (vector<int>& Nums,intKintt) {if(K <0) {            return false; }        Set<int>window;  for(inti =0; I < nums.size (); ++i) {if(I >k) {window.erase (nums[i-k-1]); } Auto Pos= Window.lower_bound (Nums[i]-t); if(pos! = window.end () && *pos-nums[i] <=t) {return true;        } window.insert (Nums[i]); }        return false; }};

"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.