Algorithm (1) array

Source: Internet
Author: User
Tags diff

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

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.