leetcode__Two Sum

来源:互联网 发布:360沙盒软件 编辑:程序博客网 时间:2024/06/01 08:54

http://oj.leetcode.com/problems/two-sum/


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,先构建一个struct,像map一样;因为在一列数中,每个数有两个属性{值,位序},所以恰好使用map可以进行存储;然后可以单独对值进行排序。

2,对于这个已排序的map数组,直观的想法就是使用“二分查找”;但是在这里要查找两个元素,所以设置两个指针,一个从头部开始,一个从尾部开始,

3,若比target小,头部指针增加;若比target大,尾部指针减小。

struct Node{    int num, pos;};bool cmp(Node a, Node b){    return a.num < b.num;}class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<int> result;        vector<Node> array;        for (int i = 0; i < numbers.size(); i++)        {            Node temp;            temp.num = numbers[i];            temp.pos = i;            array.push_back(temp);        }        sort(array.begin(), array.end(), cmp);        for (int i = 0, j = array.size() - 1; i != j;)        {            int sum = array[i].num + array[j].num;            if (sum == target)            {                if (array[i].pos < array[j].pos)                {                    result.push_back(array[i].pos + 1);                    result.push_back(array[j].pos + 1);                } else                {                    result.push_back(array[j].pos + 1);                    result.push_back(array[i].pos + 1);                }                break;            } else if (sum < target)            {                i++;            } else if (sum > target)            {                j--;            }        }        return result;    }};

2,参考哈希算法,这是一个很有趣的想法,但是自我感觉还没掌握。


class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<int> result;        map<int,int> mapping;        for (int i=0; i<numbers.size(); i++)        {            if (mapping[ target - numbers[i]] > 0)            {                result.push_back(mapping[ target - numbers[i]]);                result.push_back(i+1);                           }            else{                mapping[ numbers[i] ] = i+1;            }        }        return result;            }};



0 0
原创粉丝点击