0%

two-sum

Two Sum – LeetCode 1

Problem

Description

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 would have exactly one solution, and you may not use the same element twice.

Example

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i = 0; i != nums.size(); ++i){
for(int j = i + 1; j != nums.size(); ++j){
if(nums[i]+nums[j] == target){
result.push_back(i);
result.push_back(j);
return result;
}
}
}
}
};

思路

从数组nums的第一项开始寻找能加和成为target的另一项,简单粗暴。时间复杂度$O(n^2$),空间复杂度$O(1)$。
耗时$189$ ms,排名$77.08\%$。

Better

思路

利用HashMap中查找操作的理论时间复杂度仅为$O(1)$来省去嵌套遍历的$O(n)$。通过建立一张表来对应所需要的nums[i] - target这一值,是以空间换时间的手段。 时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$9$ ms,排名$45.75\%$。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> val2index;

// Map first index to value
val2index[nums[0]] = 0;

for (int i=1; i < nums.size(); ++i) {
// Find Complements in map
int complement = target - nums[i];
unordered_map<int,int>::const_iterator found = val2index.find(complement);
if (found != val2index.end()) {
return vector<int>({found->second,i});
}

// Map all index of nums to values
val2index[nums[i]] = i;
}
}
};