leetcode1题 题解 翻译 C语言版 Python版

1. Two Sum

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

1. 两数之和

给定一个整型数组,返回两个和为指定目标的数的下标。

你可以假定每个输入都肯定有一组解。

例如:

给定数组

nums = [2, 7, 11, 15],
目标
target = 9,

因为

nums[0] + nums[1] = 2 + 7 = 9,
所以返回两个数为

[0, 1].
更新(2016/2/13):

返回格式改成0开始下标的了。请仔细阅读上面的描述。


思路:

此题可以暴力计算,遍历一遍时每遍历到一个数就固定他,然后从后面找有没有和他加起来和为目标的。这样是两重循环。

如果用一重循环解决问题,可以遍历一遍,在每遍历到一个数时将其值与下标以键值对的方式记录到map中去(python中称作dict)。这样每遍历一个数就先在map中查找有没有(target-当前数)的数,有的话就取出其下标,与当前下标合成答案。没有的话就将将当前值与下标加入map。

在python中有自带的哈希表工具,叫作字典dict。c语言中没有此工具,好在leetcode加入了uthash的头文件。关于uthash的使用既可以直接调用宏连续使用,也可以再次封装成一系列的函数来使用,需要注意的有:

添加记录时HASH_ADD_INT的第二个变量为结构体中key变量的名字。

每次都要清空哈希表,在uthash中只需要将哈希表置NULL即可。


直接使用uthash:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
 struct value2index{
     int value;
     int index;
     UT_hash_handle hh;
 };
 
int* twoSum(int* nums, int numsSize, int target) {
    struct value2index *v2i = NULL;
    for (int i = 0; i < numsSize; i++){
        int num = target - nums[i];
        struct value2index *tmp;
        HASH_FIND_INT(v2i, &num, tmp);
        if (tmp != NULL){
            int *ans = (int*)malloc(sizeof(int) * 2);
            ans[0] = tmp->index;
            ans[1] = i;
            return ans;
        }
        else{
            tmp = (struct value2index*)malloc(sizeof(struct value2index));
            tmp->value = nums[i];
            tmp->index = i;
            HASH_ADD_INT(v2i, value, tmp);
        }
    }
    return NULL;
}


封装成函数后使用uthash,leetcode上所有使用uthash的地方都可以直接复制封装的这几个函数直接使用

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
 struct Dict{
     int key;
     int value;
     UT_hash_handle hh;
 };
 
 struct Dict *dicts = NULL;
 
 void add_dict(struct Dict *dict){
     HASH_ADD_INT(dicts, key, dict);
 }
 
 struct Dict *find_dict(int key){
     struct Dict *dict;
     HASH_FIND_INT(dicts, &key, dict);
     return dict;
 }
 
int* twoSum(int* nums, int numsSize, int target) {
    dicts = NULL;
    for (int i = 0; i < numsSize; i++){
        struct Dict *dict = find_dict(target - nums[i]);
        if (dict != NULL){
            int *ans = (int*)malloc(sizeof(int) * 2);
            ans[0] = dict->value;
            ans[1] = i;
            return ans;
        }
        else{
            dict = (struct Dict*)malloc(sizeof(struct Dict));
            dict->key = nums[i];
            dict->value = i;
            add_dict(dict);
        }
    }
    return NULL;
}


python版本:

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





  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值