[leetcode] 1. Two Sum

来源:互联网 发布:视频播放插件video.js 编辑:程序博客网 时间:2024/06/12 01:25

Question:

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].

Solution 1:

暴力解,对每个数搜后续数看是否符合。

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

时间复杂度 : O(n²)
空间复杂度 : O(1)

Solution 2:

用map记录每个出现过的数字和对应下标,对于一个新的数,直接查看map中是否有对应符合的数。
一开始把 mapping[nums[i]] = i; 放在了for循环开头,导致当输入为[3,3], target为6时无法得到正确答案。原因是没有考虑相同元素为输入且他们的和为target的情况,后来把正在考虑的元素先不放入map中解决这个问题。

class Solution {public:    vector<int> twoSum(vector<int> &nums, int target) {        unordered_map<int, int> mapping;        for (int i = 0; i < nums.size(); i++) {            int diff = target - nums[i];            auto pos = mapping.find(diff);            if (pos != mapping.end()) {                vector<int> result;                result.push_back(mapping[diff]);                result.push_back(i);                return result;            }            mapping[nums[i]] = i;        }    }};

时间复杂度 : O(n)
空间复杂度 : O(n)