您的位置:首页 > 其它

LeetCode #001 Two Num

2015-07-04 22:59 375 查看

001 Two Num

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

思路1:

用STL Map,将数据存入Map,而后查找First和Target-First是否都存在,如都存在,输出他们的下标。(即First,Target-First对应的Value).

迭代器iterator两个域,iterator->first对应Key,iterator->second对应Value.

循环遍历Nums,检测Map,跳过Nums下标为Map-Value的元素。(重要)

代码:

class Solution {
public:
vector<int> twoSum(vector<int> &nums, int target) {
vector<int> solve;
map<int, int> Map;
if (nums.size() < 2){
return solve;
}
int i;
for (i = 0; i < nums.size(); i++){
Map[nums[i]] = i;
}
for (i = 0; i < nums.size(); i++) {
int temp = target - nums[i];
if (Map[temp]!=NULL){
//this if is important
if(i == Map[temp]){
continue;
//Map's value don't need in 'for' fuction.
}
solve.push_back(i+1);
solve.push_back(Map[temp]+1);
return solve;
}
}
return solve;
}
};
*/


思路2

分配一个数组空间,将数据拷贝至A

将A数组排序

建立两个查找指针头指针X,尾指针Y,依次相加比较指针所指的值E,F

E大于F Y++

E小于F X++

当指针相等或相交时退出循环

提前退出循环说明找到了E+F=target

遍历nums,当值与找到的E,F相等时,将相应的下标Push进Vector

代码

int compare(const void* a,const void* b)
{
return *(int*)a - *(int*)b;
}
class Solution
{
public:
vector<int> twoSum(vector<int>& nums, int target)
{
//vector<int>temp;
vector<int>index;
int len = nums.size();
int *temp = new int[len];
for(int i = 0; i < len; i++)
temp[i] = nums[i];
//for(int i = 0; i < len;i++)
//  temp.push_back(nums[i]);
//sort(temp.begin(),temp.end());
qsort(temp,len,sizeof(int),compare);
int left = 0;
int right = len - 1;
while(left < right)
{
if((temp[left] + temp[right]) > target)
right--;
else if((temp[left] + temp[right]) < target)
left++;
else
break;
}
for(int i = 0; i < len; i++)
{
if(nums[i] == temp[left] || nums[i] == temp[right])
index.push_back(i + 1);
}
delete []temp;
return index;
}
};


知识点

在一个数组中查找指定元素

对数组元素进行排序

得到排序数组中比某数小或大的区域(该数不一定存在在数组内)

知道一组值,求与这组值有关的另一组值

方法2的一种特殊思路.

官网给出的Solution

O(n2) 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(n2).

O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  markdown leetcode