write in front : study the operating system, used to C, but in doing algorithmic problems even building large systems, C is really a nightmare. It is better to use C + +, the basic algorithm is very mature, and can be based on this implementation of more complex algorithms. Then write algorithms to pick up a long time without the C + + bar!
title : K-difference pairs (K-diff Pairs) in the array. Enter as an array A and an integer k, find all the values in the array to pairs (i,j), where the absolute value of the difference between a[i] and A[j] is K. such as "3,1,4,1,5", k=2,ouput=2, such a difference pair is (1,3) and (3,5), where 1, although the array appears 2 times, but only one time. (Title: Https://leetcode.com/problems/k-diff-pairs-in-an-array/#/description)
idea : Put the elements in the array into the map, the key is the value in the array, and value is the number of times the value appears in the array. After building the map, iterate over the array to see if the value of a[i]+k exists in the array.
answer : https://github.com/honpey/codebox/blob/master/leetcode/array/p532.cpp
Why do you use Unordered_map? Because the later involved in the search, unordered_map lookup is not slower, but the insertion of a little bit, the problem is not a small amount of data, so the direct use of unordered_map. Unordered_map is implemented using a hash table , where the search time complexity is O (1), as long as access to the not-ordered scenario is applied, but map is implemented using Rb-tree, search, INSERT, The time complexity of the deletion is O (logn), but this does not mean that unordered_map is necessarily good or depends on the amount of data. Unordered_map and Hash_map did the same thing, but Hash_map still didn't write c++11.
relevant knowledge points :
Data structures in C + +: Map,vector,auto variables
When using a struct in c++11, such as unordered_map, compile-time add: g++ -std=c++11 -o [email protected] $<
Previous error Ideas :
Algorithm (1) array