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 ;}};