Leecode刷題之旅-C語言/python-1.兩數之和

開學後忙的焦頭爛額(懶得很),正式開始刷leecode的題目了。node

想了想c語言是最最基礎的語言,雖然有不少其餘語言很簡單,有更多的函數能夠用,但c語言能煅煉下本身的思考能力。python則是最流行的語言。python

作題用的是 xcode的 leecode插件 很是的方便。順序從簡單到難。開始。數組

[1] 兩數之和
*
* https://leetcode-cn.com/problems/two-sum/description/
*
* algorithms
* Easy (44.20%)
* Total Accepted:    232.9K
* Total Submissions: 526.9K
* Testcase Example:  '[2,7,11,15]\n9'
*
* 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
*
* 你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。
*
* 示例:
*
* 給定 nums = [2, 7, 11, 15], target = 9
*
* 由於 nums[0] + nums[1] = 2 + 7 = 9
* 因此返回 [0, 1]
 
最開始的想法就是先弄個最簡單的思路。
在數組中,經過兩個參數i和j,進行循環,而後判斷相加等不等於 目標值target。
int* twoSum(int* nums, int numsSize, int target) {
    int i,j,count=0;//count爲統計的次數
    int *a = (int*)malloc(2*sizeof(int));//爲a分配內存   
   //循環遍歷數組
    for(i=0;i<numsSize;i++){
        for(j=i+1;j<numsSize;j++){
            if(nums[i]+nums[j]==target){
                a[0]=i;
                a[1]=j;
                count=1;//統計次數設爲1              
            }
        }
        if(count==1) break; //若找到,則退出。
    }
    return a;
}

這裏有兩個點要注意:xcode

1.要對返回的數組進行動態的分配內存,否則會報錯。數據結構

2.設置一個count,記錄是否找到成功的值,找到一次後由於題目要求不能重複利用,其實就能夠退出了。app

 

這道題用c語言作能夠經過,可是時間複雜度達到了O(n²) 有另外一種辦法就是用哈希表,在別的一些高級腳本語言中能夠用字典的方式,只須要一次遍歷就能夠。函數

可是c語言中須要本身寫哈希表的東西。這裏順便複習下數據結構的哈希表spa

參考:https://blog.csdn.net/hang404/article/details/84764531.net

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
struct node {
    long val;
    int index;
    struct node* next;
};
void insert(struct node** hashTable, long val, int index, int n) {
    int t = abs(val) % n;
    struct node* temp = hashTable[t];
    // head-add
    struct node* add = (struct node*)malloc(sizeof(struct node));
    add->val = val;
    add->index = index;
    add->next = temp->next;
    temp->next = add;
}
int search(struct node** hashTable, long target, int n) {
    int index = abs(target) % n;
    struct node* temp = hashTable[index]->next;
    while(temp) {
        if(temp->val == target) {
            return temp->index;
        }
        temp = temp->next;
    }
    return -1;
}
void freeHashTable(struct node** hashTable, int n) {
    int i = 0;
    struct node *temp = NULL, *delete = NULL;
    for(i = 0; i < n; i++) {
        temp = hashTable[i];
        delete = temp;
        while(temp) {
            delete = temp;
            temp = temp->next;
            free(delete);
        }
    }
    free(hashTable);
}
int* twoSum(int* nums, int numsSize, int target) {
    int i = 0, j = 0;
    int n = numsSize, index = 0;
    int* result = NULL;
    struct node** hashTable = (struct node**)malloc(n * sizeof(struct node*));
    // init head node
    for(i = 0; i < n; i++)
        hashTable[i] = (struct node*)calloc(1, sizeof(struct node));
    for(i = 0; i < n; i++) {
        index = search(hashTable, target - nums[i], n);
        if(-1 == index)
            insert(hashTable, nums[i], i, n);
        else {
            result = (int*)malloc(sizeof(int) * 2);
            result[0] = index;
            result[1] = i;
            freeHashTable(hashTable, n);
            return result;
        }    
    }
    freeHashTable(hashTable, n);
    return result;
}

關於哈希表的概念和c語言中哈希表的設計:插件

https://blog.csdn.net/qq_34888036/article/details/80880487

------------------------------------------------------------------------------------------------------------------------------------------------------------

python:

#
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 兩數之和
#
# https://leetcode-cn.com/problems/two-sum/description/
#
# algorithms
# Easy (44.78%)
# Total Accepted:    257.1K
# Total Submissions: 574K
# Testcase Example:  '[2,7,11,15]\n9'
#
# 給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
# 
# 你能夠假設每種輸入只會對應一個答案。可是,你不能重複利用這個數組中一樣的元素。
# 
# 示例:
# 
# 給定 nums = [2, 7, 11, 15], target = 9
# 
# 由於 nums[0] + nums[1] = 2 + 7 = 9
# 因此返回 [0, 1]
# 
# 
#
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)  #獲取nums的長度          
        d = {}         #建立空字典
        for x in range(n):
            a = target - nums[x]    #構成target和須要的差值
            if nums[x] in d:
                return d[nums[x]],x  #返回兩個位置
            else:
                d[a]=x               #將當前位置所需的差值和自身位置存入字典中

這段代碼我還理解了不少遍。

好比從2開始,字典對2的存儲是: 7:0

就是當前位置須要的差值,和自身的位置。

而後尋找到下一個 a此時等於2,若是字典中沒有這個7的話,那字典中存儲的就應該是 2 :1 也就是它須要2能夠合成target,自身的位置是1。

若是有這個7的話,那麼就返回 須要差值是7的那個數的位置,和當前位置也就是x。返回的就是 d[7]和1 也就是 0和1

大意就是 從這段數組中,邊存便檢查,字典中存放target與每一個數的差值和自身的位置,在後面若是查找到當前的數和字典中的差值相等,就返回

字典中對應的位置和自身的位置。沒查到的話,就把當前數所需差值和當前的位置存放到字典中。

相關文章
相關標籤/搜索