Leetcode: Two Sum

来源:互联网 发布:淘宝网上怎么复制链接 编辑:程序博客网 时间:2024/06/05 11:28

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

第一反应:

#include <algorithm>class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        vector<int> tmp(numbers);        sort(tmp.begin(), tmp.end());        for (int i = 0, j = tmp.size() - 1; i < j;) {            int sum = tmp[i] + tmp[j];            if (sum < target) {                ++i;            }            else if (sum > target) {                --j;            }            else {                int index1 = -1;                int index2 = -1;                for (int k = 0; k < numbers.size() && (index1 == -1 || index2 == -1); ++k) {                    if (numbers[k] == tmp[i] && index1 == -1) {                        index1 = k;                    }                    else if (numbers[k] == tmp[j] && index2 == -1) {                        index2 = k;                    }                }                         vector<int> result;                result.push_back(min(index1+1, index2+1));                result.push_back(max(index1+1, index2+1));                return result;            }        }    }};

网上看了一下,还有其他方法:

1. 用一个struct保存value和index,这样就可以省去查找原数组中索引这一步了,不过增加了空间。

2. 用map来实现,也是O(nlgn),不过空间需要的就更多了。

=========================第二次=======================

用哈希表,时间复杂度O(n),代码也很简洁。需要注意单个数算两次的情况 - 这类问题用hash来解决都需要考虑这种特例。比如(3, 2, 4),target为6。

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        unordered_map<int, int> gaps;        for (int i = 0; i < numbers.size(); ++i) {            gaps[target - numbers[i]] = i + 1;        }                for (int i = 0; i < numbers.size(); ++i) {            auto iter = gaps.find(numbers[i]);            if (iter != gaps.end() && iter->second != i + 1) {                vector<int> v;                v.push_back(i+1);                v.push_back(iter->second);                return v;            }        }    }};

0 0