最近发现自己代码能力很菜,为了明年秋招能找到合适的工作,决定从现在开始刷LeetCode,开个博客记录一下刷题遇到的问题,也方便后面查看回顾。
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].
题意很简单,数组中两个值相加等于指定的值,返回这两个值的下标:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target)
{ int *a = (int*)malloc(2*sizeof(int));
for (int i=0;i<numsSize;i++)
{ for (int j=i+1;j<numsSize;j++)
{ if (nums[i]+nums[j]==target)
{ a[0]=i;
a[1]=j;
}
else
continue;
}
}
return a;
}
由于自己对C语言相对来说熟悉一点,还是倾向于用C语言,python学的不上不下的,很尴尬,语言这种东西很奇妙,你第一次学的什么语言,后面遇到问题就总是习惯用这种语言思考,即使可以用别的语言写出来,好像也是在“母语”基础上翻译一样。OK,后面再加强python的训练吧。
这里遇到的问题是开始是定义一个数组a来存放下标,我开始写的是 int a[2]; 报错信息:
load of null pointer of type 'const int'
后来改成 int *a = (int*)malloc(2*sizeof(int)); 通过了运行。
后来查看资料才知道,这是初学者很容易犯的错误,前面加上static就行了,static int a[2];顺利通过。
OK,用两个for循环通过了测试,但是这是最暴力的方法,时间复杂度为O(n^2),基本上是最差的解法了,下面就要优化代码,降低时间复杂度。
参考链接:
https://www.cnblogs.com/Elaine-DWL/p/8097944.html
https://www.jianshu.com/p/7d8719358000
https://blog.youkuaiyun.com/yake827/article/details/50995807