您的位置:首页 > 其它

LeetCode No.1 Two Sum

2016-09-02 12:01 579 查看
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].


UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.
====================================================================================================================================
第一次发博客,纪念一下。。。。。(割)

这道理标签是Easy,说明不难,事实也不是很难。题目的大致意思是:给一个整型数组和一个整数,并且这个整数是数组里面唯一的一对整数之和,求这一对整数的下标。

正常水的人一般想法就是逐对扫一遍,两重循环,复杂度就是O(N^2)。不过这里没有给出数组的长度,不知道会不会超时,暂且试一下吧,居然能过Orz。。。

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
ans.clear();
int n = nums.size();
for ( int i = 0 ; i < n - 1 ; i ++ )
{
for ( int j = i + 1 ; j < n ; j ++ )
{
if ( i != j )/* 反例:nums = [3,2,4] , target = 6 */
{
if ( nums[i] + nums[j] == target )
{
ans.push_back ( i );
ans.push_back ( j );
return ans ;
}
}
}
}
return ans;
}
};
通过是通过了,但是能不能有复杂度更低的算法呢?我想到了STL中的map,map是映射过程,将target - nums[i]映射到i+1,现在你可能会想为什么是i+1而不是i,因为映射到i的话下标为0的就找不到了。然后遍历一遍数组,首先判断是否在映射表里面,如果在的话说明已经找到了符合条件的整数对,直接返回就行,否则继续将target - nums[i]映射到i+1,如此循环该过程。计算一下这个复杂度,首先遍历数组需要O(N),map中查找需要O(logN),所以复杂度为O(N*logN)

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

如有错误,求告知改正~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: