[leetcode] Two Sum

来源:互联网 发布:淘宝黑色半高领薄毛衣 编辑:程序博客网 时间:2024/06/11 00:48

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

A1 将数组按照关键值排序,从两端遍历寻找和为target的index:88ms

struct Node{    int value;    int index;    Node() {value=0; index=0;}    Node(int v, int i):value(v), index(i) {}};bool compare(const Node &x, const Node &y){    return x.value<y.value;}class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target)     {        vector<Node> nodes;        for (int i=0; i<numbers.size(); i++)        {            nodes.push_back(Node(numbers[i],i+1));        }                sort(nodes.begin(),nodes.end(),compare);                int i = 0, j = nodes.size()-1;        while (nodes[i].value + nodes[j].value != target)        {        if (nodes[i].value + nodes[j].value > target)        j--;        else        i++;        }                vector<int> res;        res.push_back(nodes[i].index<nodes[j].index?nodes[i].index:nodes[j].index);        res.push_back(nodes[i].index>nodes[j].index?nodes[i].index:nodes[j].index);                return res;        }};

A2 建立哈希表,扫描一遍数列:92ms

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target)     {        vector<int> res;        map<int, vector<int>> number_map;        for (int i=0; i<numbers.size(); i++)        {            if (number_map.count(target-numbers[i]))            {                res.push_back(number_map[target-numbers[i]][0]);                res.push_back(i+1);                return res;            }            number_map[numbers[i]].push_back(i+1);        }    }};




0 0