1. 程式人生 > >leetcode1題 題解 翻譯 C語言版 Python版

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 []