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

leetcode_01_Two sum

时间:2015-02-12 18:32:47      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   two pointer   array   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


Two sum

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 把原始数据排序
2 用两个指标start和end从数组两头往中间走,如果两个当前数字的和比目标数字小,那么start往后走一位。如果两个当前
数字的和比目标数字大,那么end往前走一位。如果两个当前数字的和等于目标数,那么我们就得到了start和end的指标。
3 找到start和end所对应数字在原始数组中的位置
*/

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
        vector<int> temp = numbers;
        sort(temp.begin() , temp.end());
        int start = 0 , end = temp.size()-1;
        while(temp[start] + temp[end] != target)
        {
            if(temp[start] + temp[end] < target)
                start++;
            else
                end--;
        }
        int i = 0;
        while(numbers[i] != temp[start])
        {
            i++;
        }
        result.push_back(i+1);
        

        int j = numbers.size()-1;
        while(numbers[j] != temp[end])
        {
            j--;
        }
		/*可能输出的下标位置会变成倒序
			Input:	[5,75,25], 100
			Output:	3, 2
			Expected:	2, 3
		*/
        if(result[0] <= j+1)
            result.push_back(j+1);
        else
            result.insert(result.begin() , j+1);//插入到begin()之前
        

        return result;
    }
};

/*方法二:Map
<K, V>为<值,下标>,map中保存的是已经扫描过的number。
这是一种很直观很自然的做法:
对于numbers[i],如果map中存在K=target-numbers[i],则要求的解为V(K=target-numbers对应的)和i;
如果不存在,则向map中添加<numbers[i], i>。
*/

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        int i, sum;
        vector<int> results;
        map<int, int> hmap;
        for(i=0; i<numbers.size(); i++)
		{
            if(!hmap.count(numbers[i]))//为什么要有这个判断?
			{
                hmap.insert(pair<int, int>(numbers[i], i));
            }
            if(hmap.count(target-numbers[i]))
			{
                int n=hmap[target-numbers[i]];
                if(n<i)
				{
                    results.push_back(n+1);
                    results.push_back(i+1);
                    //cout<<n+1<<", "<<i+1<<endl;
                    return results;
                }
            }
        }
        return results;
    }
};

leetcode_01_Two sum

标签:c++   leetcode   two pointer   array   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43764391

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