LeetCode1--TwoSum

题目: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、第一次审题被误解,看到举例的Input,我以为给定的是有序数组,于是,写出下面的程序:

/**
*排序数组可以采取的方法:
*取头尾两个数字相加,比较结果和target数值,如果相等,则返回index位置,否则,由两头向中间递增或者递减。
*/
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        int begin = 0;
        int end = nums.size()-1;
        while(begin < end){
            if(nums[begin]+nums[end]==target){
                result.push_back(begin+1);
                result.push_back(end+1);
                return result;
            }else{
                nums[begin]+nums[end]>target?end--:begin++;
            }
        }
        return result;
    }
};

 

提交之后发现报错,提示信息:

Input:	[3,2,4], 6
Output:	[1,3]
Expected:	[2,3]

发现系统的测试用例Input是无序的,所以这种方法不可行。

 

2、重新做了一下,用map来存储中间生成的结果:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        map<int,int> store;
        for(int index=0;index<nums.size();index++){
            if(store.count(nums[index]) > 0){
                result.push_back(store[nums[index]]);
                result.push_back(index+1);
                return result;
            }else{
                store[target-nums[index]]=(index+1);
            }
        }
        return result;
    }
};

测试通过。

posted @ 2015-06-12 17:10  踏雪公子  阅读(129)  评论(0编辑  收藏  举报