7: two sum

来源:互联网 发布:淘宝如何自己刷信誉 编辑:程序博客网 时间:2024/06/02 06:26

注:本题的解法思想及参考的代码来自于https://github.com/soulmachine/leetcode#leetcode题解

题目: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

解析1:用一个哈希表,存储每个数对应的下标,复杂度 O(n)

解题代码如下:

class Solution {public:        vector<int> twoSum(vector<int>& nums, int target) {                unordered_map<int, int> mapping; // 数组nums 中的元素及对应下标                for (int i = 0; i != nums.size(); ++i)                        mapping[nums[i]] = i;                for (int i = 0; i != nums.size(); ++i) {                        const int gap = target - nums[i];                        if (mapping.find(gap) != mapping.end() && mapping[gap] > i)                                return vector<int>{i + 1, mapping[gap] + 1};                }        }};

解析2:先排序然后左右夹逼,排序O(nlgn),左右夹逼O(n),总的时间是O(nlgn),但是这个方法返回的是下标,不是数字本身,因此不是本题的解法,但其代码如下:

//在一个数组中寻找两个数,使它们之和//等于 target//先将数组排序然后左右夹逼vector<vector<int>> twoSum(vector<int>& nums, const int target){        vector<vector<int>> result;        if (nums.size() <= 1)                return result;        sort(result.begin(), sort.end());        auto first  = result.begin(), last = result.end() - 1;        while (first < last) {                if (*first + *last < target) {                        ++first;//                      while (first < last && *(first - 1) == *(first))//                              ++first;                }                else if (target < *first + *last) {                        --last;//                      while (first < last && *(last + 1) == *last)//                              --last;                }                else {                        result.push_back(vector<int>{*first, *last});                        ++first;                        --last;                        while (first < last && *first == *(first - 1))                                ++first;                        while (first < last && *last == *(last + 1))                                --last;                }        }        return result;}
0 0
原创粉丝点击