码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】2. Two Sum

时间:2015-09-05 15:04:42      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

提示:

此题非常常见,解决思路通常可以有两种,一种是使用哈希表,其时间复杂度为O(n),另一种是对数组进行排序,时间复杂度是O(nlogn)。不过实际执行下来是第二种的耗时更少。所以有时候在数据规模不大的时候,系数也是挺关键的一个因素。

代码:

哈希表方法:

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

 排序方法:

class Solution
{
public:
    vector<int> twoSum(vector<int>& numbers, int target)
    {
        vector<int> tmpNumbers(numbers.begin(), numbers.end());
        sort(tmpNumbers.begin(), tmpNumbers.end());

        int val1 = -1;
        int val2 = -1;
        int i = 0;
        int j = tmpNumbers.size() - 1;
        while(i < j) {
            if(tmpNumbers[i] + tmpNumbers[j] < target) ++i;
            else if(tmpNumbers[i] + tmpNumbers[j] > target) --j;
            else {
                val1 = tmpNumbers[i];
                val2 = tmpNumbers[j];
                break;
            }
        }

        vector<int> result;
        for(int i = 0; i < numbers.size(); ++i) {
            if(numbers[i] == val1 || numbers[i] == val2) result.push_back(i + 1);
            if(2 == result.size()) return result;
        }
        return result;
    }
};

【LeetCode】2. Two Sum

标签:

原文地址:http://www.cnblogs.com/jdneo/p/4783211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!