Two Sum--LeetCode

来源:互联网 发布:国际金融统计数据库 编辑:程序博客网 时间:2024/05/22 05:20

Two Sum

(原题链接:点击打开链接)

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 thesame element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

看到题目首先想到的是双层遍历,已知一个加数然后去寻找另一个加数,时间复杂度为O(N^2)
class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> sum;        int length = nums.size();        for(int i = 0; i < length; i++)        {            int num = target - nums[i];            for (int j = i + 1; j < length; j++)            {                if (num == nums[j])                {                    sum.push_back(i);                    sum.push_back(j);                    return sum;                }            }        }    }};

对该算法进行优化,我们可以想到刚才算法重复遍历多次后面的元素。所以我们可以用map来存储每个元素的索引,这样就可以在常数时间内获取某个元素的索引。这样则只需遍历一遍数组。时间复杂度变为O(N)。
class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int> sum;        unordered_map<int, int> hash;        int length = nums.size();        for(int i = 0; i < length; i++)        {            int num = target - nums[i];            if (hash.find(num) != hash.end())            {                sum.push_back(hash[num] - 1);                sum.push_back(i);                return sum;            }            hash[nums[i]] = i + 1;        }    }};



原创粉丝点击