1. 程式人生 > >【leetcode】兩數之和(C、Python解答)

【leetcode】兩數之和(C、Python解答)

題目: 給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。

你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

C解答: 簡單粗暴的雙層迴圈:

int* twoSum(int* nums, int numsSize, int target) {
    static int a[2];
    int i,j;
    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;
            }
        }
    }
    return a;
}

Python解答: 方法1:簡單粗暴的雙層迴圈,這是最容易想到的方法,但是無法通過時間複雜度檢驗。此處略。

方法2:算出target-nums[i],再查算出的該值是否存在於nums中,存在:查索引;不存在:下一個。此方法的時間複雜度明顯低於方法一。

程式碼:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        answer=[]
        for i in range(0,len(nums)):
            a=target-nums[i]
            if a in nums:
                j=nums.index(a)
                if i==j:
                    continue
                else:
                    answer.append(i)
                    answer.append(j)
                    break
        return answer

方法3:百度之後發現了一個更優解,建立一個字典,通過迴圈把 target - nums[x]作為鍵,x作為值存入字典,邊存邊檢查當前正在處理的nums[x]是否存在於字典中,存在:返回字典中nums[x]的值,和當前正在使用的x的值。 此方法的時間複雜度優於方法2。

程式碼:

class Solution:
    def twoSum(self,nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n = len(nums)
        d = {}
        for x in range(n):
            a = target - nums[x]
            if nums[x] in d:
                return d[nums[x]],x
            else:
                d[a] = x