LeetCode_1.Two Sum

Problem Description:

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:

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

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

这个题的大致意思就是输入一串数nums和目标数target,找出其中两个数和为目标数的下标,并返回。

这道题比较简单,一个遍历就能解决。有两种思路:1、直接找两个数判断和是否为目标数,两重循环,最坏情况复杂度O(N^2);2、用目标数减去其中一个数,再在数组中查找,最坏复杂度也是O(N*查找算法的复杂度)。如果用二分法查找,则为O(N*log(N));

再来看一下所给的函数接口:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
}

传递三个形参,数组首地址、数组大小、目标数。返回指针。从返回指针就可以知道,需要malloc,不然的话函数里面定义的数组会被直接释放,只有malloc开辟的内存是放在堆里面的,不会直接释放。

源代码:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int i,j,k=0;
    int sum;
    int t[numsSize],*s;
    
    for(i = 0; i < numsSize; i++)
    {
    	sum = nums[i];
    	for(j = i+1; j< numsSize; j++)
    	{
    		sum += nums[j];
    		if(sum == target)			/* 若找到,则存储下标 */ 
    		{
    			t[k++] = i;
    			t[k++] = j;
			}
            sum = nums[i];              /* 重新赋初值 */
		}
	}
    
	s = (int *)malloc(k*sizeof(int));
	for(i = 0; i < k; i++)
		s[i] = t[i];
	return s;
}

运行结果:

我用的是第一种算法,从运行时间可以看出,这个算法一般;可以试着用第二种算法改进,鉴于目前时间关系以后有时间在编写。欢迎探讨,谢谢!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值