leetcode 刷题题解(c++) 1.Two Sum (hash表,排序+二分查找)

来源:互联网 发布:淘宝上最好卖的东西 编辑:程序博客网 时间:2024/06/09 19:04

题目描述:

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

解法:

a. 排序+二分查找

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<struct Node> tmp;        for(int i=0;i<numbers.size();i++)        {            struct Node node_tmp;            node_tmp.num=numbers[i];            node_tmp.pos=i;            tmp.push_back(node_tmp);        }        int beg=0,end=numbers.size()-1;        sort(tmp.begin(),tmp.end(),cmp);        while(beg<=end)        {            if(tmp[beg].num+tmp[end].num==target)            {                if(tmp[beg].pos>tmp[end].pos)                {                    result.push_back(tmp[end].pos+1);                    result.push_back(tmp[beg].pos+1);                }                else                {                    result.push_back(tmp[beg].pos+1);                    result.push_back(tmp[end].pos+1);                }                return result;            }            else if(tmp[beg].num+tmp[end].num>target)                end--;            else                beg++;        }        return result;    }};

b.hash表

i)遍历两遍

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> num_map;        vector<int> res;        for (int i = 0; i < nums.size(); i++) {            num_map[nums[i]] = i;        }        for (int i = 0; i < nums.size(); i++) {            int tmp = target - nums[i];            if (num_map.find(tmp) != num_map.end() && num_map[tmp] != i){                res.push_back(i);                res.push_back(num_map[tmp]);                break;            }        }        return res;    }};
ii)遍历一遍

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> num_map;        vector<int> res;        for (int i = 0; i < nums.size(); i++) {            int tmp = target - nums[i];            if (num_map.find(tmp) != num_map.end() && num_map[tmp] != i){                int beg = i > num_map[tmp] ? num_map[tmp] : i;                int end = i > num_map[tmp] ? i : num_map[tmp];                res.push_back(beg);                res.push_back(end);                break;            }            num_map[nums[i]] = i;        }        return res;    }};

0 0
原创粉丝点击