LeetCode --- 1. Two Sum

110 篇文章 0 订阅

题目链接:Two Sum

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哦)。思路如下:

1. 暴力查找

这是最简单直接的方式,两层循环遍历数组。不上代码了。。。

时间复杂度:O(n2)

空间复杂度:O(1)

2. 排序后查找

首先对数组排序。不过由于最后返回两个数字的索引,所以需要事先对数据进行备份。然后采用2个指针l和r,分别从左端和右端向中间运动:当l和r位置的两个数字之和小于目标数字target时,r减1;当l和r位置的两个数字之和大于目标数字target时,l加1。因此只需扫描一遍数组就可以检索出两个数字了。最后再扫描一遍原数组,获取这两个数字的索引。

时间复杂度:O(nlogn)(取决于排序时间复杂度)

空间复杂度:O(n)(取决于排序空间复杂度以及备份数组的空间复杂度)

 1 class Solution{
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target)
 4     {
 5         vector<int> v(numbers);
 6         sort(v.begin(),v.end());
 7         
 8         int l = 0, r = v.size() - 1;
 9         while(l < r)
10         {
11             if(v[l] + v[r] == target)
12                 break;
13             else if(v[l] + v[r] > target)
14                 -- r;
15             else
16                 ++ l;
17         }
18         
19         vector<int> index;
20         for(int i = 0, n = 2; i < numbers.size(); ++ i)
21             if(v[l] == numbers[i] || v[r] == numbers[i])
22             {
23                 index.push_back(i + 1);
24                 if(-- n == 0)
25                     break;
26             }
27         
28         return index;
29     }
30 };

3. Hash表

对每个出现的数字存入Hash表(set)中,这样可以以O(1)的时间判断每个数字是否在数组中出现过。因此只需要遍历一次数组即可。

时间复杂度:O(n)

空间复杂度:O(n)

 1 class Solution{
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target)
 4     {
 5         vector<int> v;
 6         map<int, int> m;
 7         for(int i = 0; i < numbers.size(); ++ i)
 8         {
 9             if(m.find(target - numbers[i]) != m.end())
10             {
11                 v.push_back(m[target - numbers[i]] + 1);
12                 v.push_back(i + 1);
13                 break;
14             }
15             m[numbers[i]] = i;
16         }
17         return v;
18     }
19 };

耶,第1道,加油。。。^_^

转载请说明出处:LeetCode --- 1. Two Sum

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值