Two Sum, twosum

Source: Internet
Author: User

Two Sum, twosum

This is the first question of leetcode. It is very simple, but if you want to reduce the running time to as little as possible, you still need to worry about it.

The questions are as follows:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input wocould haveExactlyOne solution, and you may not useSameElement twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums [0] + nums [1] = 2 + 7 = 9

Return [0, 1].

A solution with a time complexity of O (n) is:


1 int * twoSum (int * nums, int numsSize, int target) 
2 {
3 int index [100001] = {0}, * index_plus_one = index + 50000; // The index starts from the 50,000th elements in the index array to avoid negative index errors.
4 for (int I = 0; I <numsSize; I ++) 
5 {
6 int rest = target-nums [I]; 
7 if (index_plus_one [rest])
 8 {
9 // if the rest index has been computed, then we can get the answer
 10 int * ans = malloc (sizeof (int) * 2); 
11 ans [0] = I; 
12 ans [1] = index_plus_one [rest]-1;
 13 return ans; 
14} 
15 else
16 index_plus_one [nums [I] = I + 1; // if the rest index has not been computed, Mark index_plus_one [nums [I] as greater than 0; 
17} 
18 return NULL; 
19}


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.