Leetcode 220 Contains Duplicate III

Source: Internet
Author: User

Leetcode 220 Contains Duplicate III
1. Problem Description

Given an integer array nums [], check whether two subscripts I and j exist. | Numsi? Numsj | ≤ t And | I? J | ≤ k .

2. methods and ideas

The general idea is: "Sliding Window" + unordered_map.
The reasoning process is as follows:
   | Numsi? Numsj | ≤ t? | Numsi/t? Numsj/t | ≤ 1 ;
From above, we can launch: |? Numsi/t ??? Numsj/t? | ≤ 1
It is equivalent: ? Numsi/t? ε {? Numsj/t ?,? Numsj/t ?? 1 ,? Numsj/t? + 1} .
We only need to maintain a window with K size and the key value is ? Numsi/t? , Value: Numsi . The nums [] array is traversed cyclically, and the absolute value of the value corresponding to the unordered _ map key set is calculated, and then the result can be determined.
For information about unordered_map in STL, refer to the official References to explain unordered_map.

Note:Unordered_map is a special hash map, which is not sorted by key value. By using the hash table algorithm, the search efficiency is O (1 ). But it will consume a certain amount of memory. During the difference calculation, the value must be converted to the long type; otherwise, overflow occurs.

Class Solution {public: bool containsNearbyAlmostDuplicate (vector
  
   
& Nums, int k, int t) {if (t <0 | k <1) return false; int I, key; unordered_map
   
    
Dict; for (I = 0; I <nums. size (); I ++) {key = nums [I]/max (1, t); // map
    
     
: Iterator it; if (dict. find (key )! = Dict. end () & abs (nums [I]-dict [key]) <= t) | (dict. find (key-1 )! = Dict. end () & abs (long) nums [I]-(long) dict [key-1]) <= t) | (dict. find (key + 1 )! = Dict. end () & abs (nums [I]-dict [key + 1]) <= t) {return true ;} // dict [key] = nums [I]; dict. insert (pair
     
      
(Key, nums [I]); if (I> = k) {dict. erase (nums [I-k]/max (1, t); // delete a key value other than the window size }}return false ;}};
     
    
   
  

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.