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

LeetCode 1: Two Sum

时间:2015-03-19 18:13:37      阅读:166      评论: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

思考:

1.首先没注意审题,以为数组是排序的,然后就用两个指针,一前一后,直到找到目标和的指针

    vector<int> twoSum(vector<int> &numbers, int target) {
        int start = 0;
        int tail = numbers.size()-1;
        vector<int> result;
        while(start<tail){
            if(numbers[start] + numbers[tail] <target){
                start ++;
            }else if(numbers[start] + numbers[tail] > target){
                tail --;
            }else{
                result.push_back(start);
                result.push_back(tail);
                return result;
            }
        }
    }

  提交后,发现Runtime Error

2.然后考虑的是暴力的方法,时间复杂度为O(n^2)

    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
        for(int i =0;i<numbers.size(); i++){
            for(int j=i+1;j<numbers.size(); j++){
                if(numbers[i] + numbers[j] == target){
                    result.push_back(i+1);
                    result.push_back(j+1);
                    return result;
                }
            }
        }
    }

  

发现Time Limit Exceeded。

3.遂寻找更快速的方法,网上参考了下,发现需要HashTable,使用STL的map来实现。

    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
        map<int,int> map_res;
        for(int i =0;i<numbers.size();i++){
            int temp = target - numbers[i];
            if(map_res[temp]){
                result.push_back(map_res[temp]+1);
                result.push_back(i+1);
            }
            map_res[numbers[i]]=i;
        }
        return result;
    }

4.发现结果还是不对,Runtime Error,错误的例子是[0,4,3,0], 0,发现原来在取map_res[0]的值对应的是0,改了下方法,使用map_res.count(temp),终于AC了

    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
        map<int,int> map_res;
        for(int i =0;i<numbers.size();i++){
            int temp = target - numbers[i];
            if(map_res.count(temp)){
                result.push_back(map_res[temp]+1);
                result.push_back(i+1);
            }
            map_res[numbers[i]]=i;
        }
        return result;
    }

  

LeetCode 1: Two Sum

标签:

原文地址:http://www.cnblogs.com/xiamaogeng/p/4351012.html

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