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].
第一次刷leetcode,选择了很久没用,但的确之前用得相对最熟练的C语言。
感觉啥都忘了,但把C语言的东西一点一点查出来,觉得自己在重新学会它还是很开心的。
求解的时候遍历的思路是对的,但有很多细节出现了问题。
emmm,最后参考了这篇博文才搞定:
https://blog.csdn.net/yang939670129/article/details/78268496
最开始的代码和改错如下:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int i,j;
int(*result)[2];[错误1:用这句定义指针数组不管用,应该用int* result = malloc(sizeof(int)*2);语句]
for(i=0;i<numsSize+1;i++)[错误2:C语言数组从0开始,所以单层循环的时候应该i<size,而不是i<size+1]
{
for(j=0;i<numsSize+1&&j=!i;j++)[错误3:不能在循环继续条件里判断,遇到i=j不就直接跳出了吗]
{
if(*(nums+i)+*(nums+j)==target)
{ *result=*(nums+i);
*(result+1)=*(nums+j);[错误4:输出的result是数组标号而不是数值,注意审题]
return result;[错误5:return应该直接放在最后,这样会每个都return一遍,这里可以用个break跳出循环]
else if[错误6:else if什么鬼,不应该就是else吗]
return 0;
}
}
}
暂时提交的版本是这样的:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int i,j;
int* result = malloc(sizeof(int)*2);
for(i=0;i<numsSize;i++)
{
for(j=1;j<numsSize;j++)
{
if(*(nums+i)+*(nums+j)==target&&i!=j)
{
*(result)=i;
*(result+1)=j;
break;
}
}
}
return result;
}
其他语言和更优版本日后再改吧。
补充一个java版本:(与C不同的地方已标粗)
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result=new int[2];
int i,j;
for(i=0;i<nums.length;i++){
for(j=i+1;j<nums.length;j++){
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
}
java的解法是以hashmap求解的:
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>(); //new一个新的hashmap,注意Integer首字母大写
int[] res = new int[2]; //数组在java中也是需要new的,注意格式
for (int i = 0; i < nums.length; ++i) {
if (m.containsKey(target - nums[i])) {
res[0] = i;
res[1] = m.get(target - nums[i]); //get(内容)来获取序号
break;
}
m.put(nums[i], i); //put()来插入value,格式为(内容,序号)
}
return res;
}
}
//在HashMap中通过get()来获取value,通过put()来插入value,ContainsKey()则用来检验对象是否已经存在。可以看出,和ArrayList的操作相比,HashMap除了通过key索引其内容之外,别的方面差异并不大。
//如果是有两个for循环,是外层i从0到nums.length-1,内层j从i到nums.length-1
//用hashmap的话,每次插入一个值,遍历之前插入的所有值
再补充一个Python版本:
(i和j不用定义可以直接用,空数组直接[],循环的形式是i in range数组,没有大括号只用写:添加元素用append)
class Solution(object):
def twoSum(self, nums, target):
result=[]
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
result.append(i)
result.append(j)
return result