leetcode 两数相加c++_leetcode 1: 找出两个数相加等于给定数 two sum

问题描述

对于一个给定的数组,找出2个数,它们满足2个数的和等于一个特定的数,返回这两个数的索引。(从1开始)

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.思路分析:

我们将求2个数的索引转换成在数组中搜索(target-nums[i])的位置;

直观想,两层遍历,固定一个元素,循环右移另一个元素,逐个测试,时间复杂度$O(n^2)$,而$O(n^2)$一般不能接受,因此需要考虑改进算法:

想法则是降低到$O(n\ lgn)$,最理想则是$O(n)$

2.测试样例:

正数、负数、0

3.特殊情况:

数组不足2个数、两数相加溢出、没有匹配的情况

4.实现

4.1 两层遍历的实现:O(n2)

#include

using namespace std;

int* twoSum(int* nums, int numsSize, int target, int* returnSize) {

returnSize = NULL;

if (numsSize < 2)

return returnSize;

int i = -1;

int j;

while (++i < numsSize-1) {

if (nums[i] >= target)

continue;

j = i;

while (++j < numsSize) {

compare_times++;

if (nums[i] + nums[j] == target)

break;

}

if (j == numsSize)

continue;

else

break;

}

if (i != numsSize-1) {

returnSize = new int [2];

returnSize[0] = i+1;

returnSize[1] = j+1;

}

return returnSize;

}

int main()

{

int nums[] = {-1, 0, 9, 5, 7, 11, 15, 20};

int target = 9;

int *index = NULL;

index = twoSum(nums, sizeof(nums)/sizeof(nums[0]), target, index);

if(index != NULL)

cout<

}

提交到leetcode 返回Time Limit Exceeded,不满足时间要求。

4.2 排序实现 O(nlgn)

首先将数组进行快速排序或者插入到二叉搜索树中,二分查找,当固定一个元素nums[i],在数组中查找target - nums[i],此时查找时间降低到O(lgn),总消耗即为O(nlgn)

4.3 线性实现-Hash表 O(n)

我们知道对元素的搜索最快则是O(1),即直接索引到,联想只能是Hash表或者是关键字索引。关键字索引(从最小到最大)会占用额外的内存空间。

由于C++有现成的hash map,所以直接采用c++。

另外我们要求的是元素的索引,即Hash表的关键字,所以我们把数组元素作为Hash表的关键字,而把数组元素的索引作为Hash表的元素值。

class Solution

{

public:

vector twoSum(const vector &nums, int target) {

vector results;

if (nums.size() < 2) {

return results;

}

map hmap;

//插入到hash map

for (int i = 0; i < nums.size(); i++) {

hmap.insert(pair (nums[i], i) ); //元素值做关键值

}

int j;

for (int i = 0; i < nums.size(); i++) {

//hmap.count(x):x在hash map中出现的次数

if (hmap.count(target - nums[i])) {

j = hmap[(target - nums[i])];

if (j < i) {

results.push_back(j+1);

results.push_back(i+1);

}

}

}

return results;

}

};

测试

int main()

{

int nums[] = {0,-3, 2, 7, 11, 15, 20};

vector nums_v(nums, nums+7);

int target = 9;

while (1) {

class Solution sol;

vector results = sol.twoSum(nums_v, target);

if(results.size())

cout<

}

getchar();

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值