LeetCode:两数之和

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41505957/article/details/83961717

https://leetcode-cn.com/problems/two-sum/description/

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) 
{
    int i,j;
	int *ans= (int *)malloc(sizeof(int)*2);         //申请所需空间
	for(i=0;i<numsSize;i++)
	{
		for(j=0;j<i;j++)
			if(nums[i]+nums[j]==target)     //找到两数之和为target
			{
				ans[0]=j;
				ans[1]=i;                 //将数存入
				return ans;                 
			}		
	}  
    return NULL;                                        //没有找到答案返回空
}

复杂度分析:

  • 时间复杂度:O(n2)O(n^2)O(n2), 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n)O(n)O(n) 的时间。因此时间复杂度为 O(n2)O(n^2)O(n2)。

  • 空间复杂度:O(1)O(1)O(1)。

扫描二维码关注公众号,回复: 4046680 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_41505957/article/details/83961717