[LeetCode][EASY]Two Sum

本文介绍了一种解决“两数之和”问题的有效算法,该算法首先对数组进行排序,然后采用双指针法从两端逼近求解,显著提高了搜索效率。

题目描述

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, and you may not use the same element twice.

Example:




   
1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解题代码

此题要求在给定的的一组数组之内找到两个相加之和为目标值的数并返回其下标,最朴素的方法是使用两次嵌套的循环结构进行数组遍历以找出两个相符的数,但是简单计算可知此算法时间复杂度为O(n^2),处理小数组尚可,对于存在大量元素的大数组,此算法所消耗时间将会十分感人。

更好的方法是考虑先对数组做一次快速排序,然后通过两个游标从数组两端向中间查找,每移动一次游标对比一下游标对应数值的和与目标数值,如果数值大于目标数值则将数值较大端的游标向中心移动一位,反之则将数值较小端的游标向中心移动一位,一直重复直到找到和符合目标数值的两个数,再遍历一次未排序的数组,寻找原始下标并返回,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdlib.h> #include <string.h> int cmp ( const void *a , const void *b ) { return * ( int * )a - * ( int * )b ; } int *twoSum ( int *nums , int numsSize , int target , int *returnSize ) { int *result = ( int * ) malloc ( sizeof ( int ) * 2 ) ; int *nums_bk = ( int * ) malloc ( sizeof ( int ) * numsSize ) ; int i , index_right , index_left ; //排序前先复制副本 memcpy (nums_bk , nums , sizeof ( int ) * numsSize ) ; //排序(从小到大)此时下标乱了,要在之后寻找原下标 qsort (nums_bk , numsSize , sizeof ( int ) , cmp ) ; //找排序后符合target的下标
    index_left = 0 ;
    index_right = numsSize - 1 ; while (index_left != index_right ) { if (nums_bk [index_left ] + nums_bk [index_right ] == target ) {
            result [ 0 ] = index_left ;
            result [ 1 ] = index_right ; break ; } else if (nums_bk [index_left ] + nums_bk [index_right ] > target ) {
            index_right --; } else {
            index_left ++; } } //查找原下标 int res_0_find = 0 ; int res_1_find = 0 ; for (i = 0 ; i < numsSize ; i ++ ) { if (nums [i ] == nums_bk [result [ 0 ] ] && res_0_find == 0 ) {
            result [ 0 ] = i ;
            res_0_find = 1 ; continue ; } else if (nums [i ] == nums_bk [result [ 1 ] ] && res_1_find == 0 ) {
            result [ 1 ] = i ;
            res_1_find = 1 ; continue ; } } *returnSize = 2 ; return result ; }

提交结果




   
1
2
3
4
√ Accepted
  √ 29/29 cases passed (8 ms)
  √ Your runtime beats 91.23 % of c submissions
  √ Your memory usage beats 6.25 % of c submissions (7.9 MB)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值