美文网首页
leetcode 1 two sum

leetcode 1 two sum

作者: clshinem | 来源:发表于2017-03-28 16:53 被阅读0次

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].```

用c语言来写
首先想到的就是双重循环(菜)
代码:

int* twoSum(int* nums, int numsSize, int target) {
static int ret[2] = {0,0};//返回的数组还是要返回指针
//int ret = (int)malloc(sizeof(int)*2)
for (int i = 0;i < numsSize;i++){
for(int j = i+1;j<numsSize;j++){
if(nums[j] == target - nums[i]){
ret[0] = i;
ret[1] = j;
return ret;
}
}

}
return NULL;

}


######这里提交的时候遇到的坑(主要还是手生):
1:`static int ret[2] = {0,0}; `这里不加static会报错
`load of null pointer of type 'const int'`
不知道是啥意思但是看到了const之后想到以前貌似见过这个坑,所以加了static就运行通过了
2:在函数最后没有加`return null`
报错`control reaches end of non-void function [-Werror=return-type]` 开始还不知道是因为什么,后来发现是没有加return。

写完之后上网上搜了一下大神的做法,用双重循环写的话是o(n2)换成hash之后可以变为o(n),python有自带的字典,可以直接很容易找到下标。
下面是c语言:

/**

  • Note: The returned array must be malloced, assume caller calls free().
    /
    int
    twoSum(int* nums, int numsSize, int target) {
    //找到min,max为target-min;
    int min = 2147483647;
    for (int i = 0;i < numsSize; i++){
    if (nums[i] < min){
    min = nums[i];
    }
    }
    int max = target - min;
    int len = max - min + 1;
    int map = (int)malloc(lensizeof(int));
    int ret = (int)malloc(2
    sizeof(int));
    for (int i = 0;i < len; i++){
    map[i] = -1;
    }
    for(int i = 0;i < numsSize;i++){
    if(nums[i] - min < len){//筛去所有不符合条件的数字,比如说:target= 9;min = 2;8就不符合。都不用进判断
    if(map[target - nums[i] - min] != -1){ //判断相加是否是target
    ret[0] = i;
    ret[1] = map[target - nums[i] - min];//map的value里面存的是满足条件的数在数组中的下标
    return ret;
    }
    }
    map[nums[i] - min] = i;
    }
    return NULL;
    }
这里使用 target-nums[i]-min 来判断是否满足下标的,我的理解是因为map放入的时候就减掉了min所以这里也要减掉一个

######python 代码

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for i in range(len(nums)):
another = target - nums[i]
if another in map:
return [map[another],i]
else:
map[nums[i]] = i

    map = {}
    for i,value in enumerate(nums):
        map[value] = i
    
    for num in nums:
        index = target - num;
        if index in map:
            return [map[num],map[index]]



相关文章

网友评论

      本文标题:leetcode 1 two sum

      本文链接:https://www.haomeiwen.com/subject/krwjottx.html