标签:
whowhoha@outlook.com
问题描述
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].
解法1:暴力破解法: O(n^2) runtime, O(1) space – Brute force: The brute force approach is
simple. Loop through each element x and find if there is another value that
equals to target – x. As finding another value requires looping through
the rest of array, its runtime complexity is O(n^2).
解法2:使用HashMap。把每个数都存入map中,然后再逐个遍历,查找是否有 target – nums[i]。 O(n) runtime O(n) space,
vector<int> twoSum(vector<int>& nums, int target){
vector<int> vec;
map<int,int> m;
for (int i = 0; i < nums.size(); i++)
{
if(m.find(target - nums[i]) != m.end())
{
vec.push_back(m[target - nums[i]] );
vec.push_back(i);
break;
}
m[nums[i]] = i;
}
return vec;
}
调用:
int a[6]={2,7,1,8,9};
vector<int> vec(a,a+5);
vector <int> vect= twoSum(vec,15);
return 1;
Two Sum II – Input array is sorted
Question:
Similar to Question [1. Two Sum], except that the input array is already sorted in
ascending order.
同上题:先排序,然后从开头和结尾同时向中间查找,原理也比较简单。O(nlogn) runtime, O(1) space
vector<int> twoSumSored(vector<int>& nums, int target){
vector<int> vecCopy(nums);
int i=0,n=2,l=0,r = nums.size()-1;
sort(vecCopy.begin(),vecCopy.end());
int j=nums.size()-1;
while(i<j)
{
int sum = nums[i]+nums[j];
if (sum <target)
{
i++;
}
else if (sum > target)
{
j--;
}
else
{
vector<int> index;
index.push_back(i+1);
index.push_back(j+1);
return index;
}
}
}
备注:vector 初始化方法,,map的使用方法
Two Sum III – Data structure design
Question:
Design and implement a TwoSum class. It should support the following operations: add and find.
add(input) – Add the number input to an internal data structure.
find(value) – Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) ? true;
find(7) ? false
我们把每个数字和其出现的次数建立映射,然后遍历哈希表,对于每个值,我们先求出此值和目标值之间的差值t,然后分两种情况来看,如果当前值不等于差值t,那么只要哈希表中有差值t就返回True,或者是当差值t等于当前值时,如果此时哈希表的映射次数大于1,则表示哈希表中还有另一个和当前值相等的数字,二者相加就是目标值。
class TwoSum {
private:
unordered_map<int,int> table;
public:
void add(int number) {
table[number]++;
}
bool find(int value) {
for(auto elem : table)
{
for (vector<string>::iterator i = v.begin(); i != v.end(); ++i);
for (auto i = v.begin(); i != v.end(); ++i);
int num1 = elem.second;
int num2 = value == (elem.first << 1) ? num1 - 1 : buffer.find(value - elem.first) != buffer.end();
if(num1 && num2){
return true;
}
}
return false;
}
};
标签:
原文地址:http://www.cnblogs.com/whowhoha/p/5738282.html