Two Sum

来源:互联网 发布:二手交易软件有哪些 编辑:程序博客网 时间:2024/06/01 22:03

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
题意:给一个整数数组,返回两个数的下标,这两个数加起来等于target

没有重复,一个数组有且仅有一个solution.

最开始想的是用two pointer, 则代码为:

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        int i = 0;        int j = nums.size() -1;        vector<int> res;        while(i < j) {            if (nums[i] + nums[j] < target) i++;            else if (nums[i] + nums[j] > target) j--;            else {                res.push_back(i);                res.push_back(j);
break;//remember to break all it will be a dead loop            }        }        return res;    }};

结果发现 nums 不是有序的, 而且不能改变数字的顺序。看了别人的题解说可以构造一个结构体把下标和数都存进去再排序。

然后想到用暴力,代码为:

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

这样时间复杂度为O(n^2)。考虑时间主要浪费在搜索两次数组,如果使用hash表,把target- nums[i]存起来,就可以变快


class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {//a,b        vector<int> res;        unordered_map<int, int> m;        for (int i = 0; i < nums.size(); i++) {            int second = target - nums[i];            if (m.find(second) != m.end()) {// i is b's index, find a                res.push_back(i);//reverse order                res.push_back(m[second]);            }            else {                m[nums[i]] = i;//store the a             }        }        return res;    }};


考虑清楚unordered_map里面应该存什么,因为要返回下标,所以unordered_map不仅要存nums[i],还有存i。然后考虑什么时候存数进map,因为当找到第二个数的时候,只知道第二个数的下标,并不知道第一个数的下标,只能在搜索到第一个数的时候就把第一个数和其下标一起存入map中,所以是map中找不到second的时候更新map。




原创粉丝点击