题目链接: https://leetcode.com/problems/two-sum/
题目难度: Easy
题目描述:
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
遍历整个数组, 对于数组中的每一个数, 在数组剩余元素中寻找满足条件的另一个数. 寻找到后, 将两个数的索引返回.
时间复杂度:
空间复杂度:
- // C++
- 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;
- }
- }
- }
- return result;
- }
- };
思路 2
先将所有元素存到一个哈希表中, 元素值作为 key, 元素索引作为 value. 然后遍历数组, 对于每一个元素, 求 target 和元素的差, 判断哈希表中是否存在以这个差为 key 的项 (需要避免同一个数加两遍的情况). 若存在, 则返回数组索引, 和这个差作为 key 对应的 value.
时间复杂度:
空间复杂度:
- // C++
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- vector<int> result;
- unordered_map<int,int> map;
- for (int i = 0; i <nums.size(); i++) {
- map[nums[i]] = i;
- }
- unordered_map<int,int>::const_iterator got;
- for (int i = 0; i <nums.size(); i++) {
- got = map.find(target - nums[i]);
- if (got != map.end()) {
- if (got->second == i) { // same element add twice
- continue;
- } else {
- result.push_back(i);
- result.push_back(got->second);
- break;
- }
- }
- }
- return result;
- }
- };
基于思路 2, 还可以再改进一下. 不一定要等到数组元素全部插入哈希表后, 再进行遍历查询, 可以边插入, 边查询表中已有元素. 这样可以让速度更快一些.
时间复杂度:
空间复杂度:
- // C++
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- vector<int> result;
- unordered_map<int, int> map;
- unordered_map<int, int>::const_iterator got;
- for (int i = 0; i <nums.size(); i++) {
- got = map.find(target - nums[i]);
- if (got != map.end()) {
- if (got->second == i) { // same element add twice
- continue;
- } else {
- result.push_back(got->second);
- result.push_back(i);
- break;
- }
- }
- map[nums[i]] = i;
- }
- return result;
- }
- };
2019 年 03 月 28 日
来源: http://www.jianshu.com/p/0f52c0761d2f