Website: https://leetcode.com/problems/two-sum/
Test instructions
Give a set of numbers, give a target value.
In this group, there are 2 numbers and equal to the target value, and the subscript of these two numbers is calculated.
Tips:
Subscript starting from 1
Clearly there must be an answer
Analysis:
There must be an answer, so there is no special case to consider.
Like what:
(1) The length of a group of numbers is less than 2.
(2) No answer
(3) and a value equal to 2 of the number of the same subscript
Solution:
Idea 1:
Sort, 2 index,1 in the past, 1 from the rear, through and compared to the target value.
But the final result is subscript, so the extra space to save the subscript and sort at the same time seems very troublesome.
Idea 2:
This set of numbers is relatively hashed, and the value and key are inverted, and it is no doubt better to sort by cardinality.
Because the range of values is unclear, map is a good choice.
Unordered_map in C + + is an unordered map, and is also the most efficient map
Take advantage of it and get a good result soon
There is no unordered_map in Java, unordered map with HashMap.
Code:
Https://github.com/LiLane/leetcode/blob/master/c%2B%2B/001-TwoSum-201504151556.cpp
Https://github.com/LiLane/leetcode/blob/master/java/001-TwoSum-201504272020.java
[Leetcode]-001-two Sum