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}