[Leetcode]-001-two Sum

Source: Internet
Author: User

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

Related Article

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.