您的位置:首页 > 其它

1. Two Sum

2016-05-13 21:45 633 查看
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.

Example: Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

Approach #1 (Brute Force) [Accepted]

The brute force approach is simple. Loop through each element xx and find if there is another value that equals to target - xtarget−x.

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


Complexity Analysis

Time complexity : O(n^2). For each element, we try to find

its complement by looping through the rest of array which takes

O(n)O(n) time. Therefore, the time complexity is O(n^2).

Space complexity : O(1).

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_multimap<int,int> um_map;
vector<int> vi;
for(int i=0;i<nums.size();i++)
um_map.insert({nums[i],i});
for(int i=0;i<nums.size();i++)
{
int temp=target-nums[i];
auto it=um_map.find(temp);
if(it!=um_map.end()&&it->second>i)
{
vi.push_back(i);
vi.push_back(it->second);
}
}
return vi;
}
};


Complexity Analysis:

-Time complexity : O(n). We traverse the list containing nn elements exactly twice. Since the hash table reduces the look up time to O(1),

the time complexity is O(n).

-Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly nn

elements.

Approach #3 (One-pass Hash Table) [Accepted]

It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back to check if current element’s complement already exists in the table. If it exists, we have found a solution and return immediately.

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_multimap<int,int> um_map;
vector<int> vi;
for(int i=0;i<nums.size();i++)
{
int temp=target-nums[i];
auto it=um_map.find(temp);
if(it!=um_map.end())
{
vi.push_back(it->second);
vi.push_back(i);
}
um_map.insert({nums[i],i});
}
return vi;
}
};


Complexity Analysis:

Time complexity : O(n). We traverse the list containing nn

elements only once. Each look up in the table costs only O(1)

time.

Space complexity : O(n). The extra space required depends on the

number of items stored in the hash table, which stores at most nn

elements.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Two-Sum