首页 > 其他 > 详细

Two Sum

时间:2015-12-31 00:08:27      阅读:189      评论: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

 

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
 这种题目就是注意转换下标和值
#include <iostream>
#include <vector>

using namespace std;

class IndexData {
public:
    IndexData(){}
    int index;
    int value;
};
/*
 * 1.生成一个vector,并对vector的 value 进行排序
 * 2.两个指针,left, right, left < right
 * 3.如果 vector[left][1] + vector[right][1] > value, right--;
 * 4.如果 vector[left][1] + vector[right][1] < value, left--;
 * 5.如果 == , 返回, 注意返回index 的大小
 *
 */
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<IndexData*> v_data;
        vector<int> res;
        size_t num_size = nums.size();
        size_t i = 0;

        for (; i<num_size; i++) {
            IndexData* d = new IndexData();
            d->index = i;
            d->value = nums[i];
            v_data.push_back(d);
        }
        sort(v_data.begin(), v_data.end(), cmp);

        int left = 0;
        int right = num_size - 1;
        while (left < right) {
            while ((left < right) && ((v_data[left]->value + v_data[right]->value) > target)) {
                right--;
            }

            while ((left < right) && ((v_data[left]->value + v_data[right]->value) < target)) {
                left++;
            }

            if ((v_data[left]->value + v_data[right]->value) == target) {
                if(v_data[left]->index < v_data[right]->index) {
                    res.push_back(v_data[left]->index + 1);
                    res.push_back(v_data[right]->index + 1);
                } else {
                    res.push_back(v_data[right]->index + 1);
                    res.push_back(v_data[left]->index + 1);
                }
                break;
            }

        }
        
        for (i=0; i<num_size; i++) {
            if (NULL != v_data[i]) {
                delete v_data[i];
                v_data[i] = NULL;
            }
        }
        
        return res;

    }

private:
    static bool cmp(const IndexData* id1, const IndexData* id2) {
        return id1->value < id2->value;
    }

};



int main() {

    vector<int> v;
    v.push_back(3);
    v.push_back(2);
    v.push_back(4);
    Solution s;

    s.twoSum(v, 6);
    return 0;
}

 

Two Sum

原文:http://www.cnblogs.com/SpeakSoftlyLove/p/5090326.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!