Catalog
  1. 1. 1. Two Sum
LeetCode Solution: 1. Two Sum

1. Two Sum

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].

解析1

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

十分暴力的写法,时间复杂度为O(n^2),直接遍历容器,寻找到下标不同,并且相加等于target的下标,然后返回

解析2

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

解析2的算法时间复杂度为O(n)理解解析2需要理解 map容器
map容器是一个存放关键字和值对的容器,关键字可以是任意类型,直接访问关键字下标可以得到对应的值,用到了C++STL里面的unordered_map
首先定义一个std::unordered_map<int, int> hashstd::vector<int> result还有我们需要的数wanted_num
进入循环,

1
2
3
4
5
6
7
8
for (int i = 0; i < nums.size(); i++) {
if (hash.find(wanted_num) != hash.end()) {
result.push_back(hash[wanted_num]);
result.push_back(i);
return result;
}
hash[nums[i]] = i;
}

访问nums的每一个元素,进入判定

  1. 如果wanted_numhash里的话,就把wanted_num的索引和当前的i放入result中,作为最后结果
  2. 如果没有在hash表里面,当前的元素放入hash表里,并设置下标为i

最后一定会把wanted_num放进hash表中,即解

时间复杂度O(n)


Author: Jsthcit
Link: http://jsthcitpizifly.com/2019/10/24/LeetCode-Solution-1-Two-Sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶

Comment