leetcode 1 two sum

2017-03-28  本文已影响0人  clshinem

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语言:

/**

这里使用 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]]



上一篇 下一篇

猜你喜欢

热点阅读