1. 程式人生 > >LeetCode1-Two Sum

LeetCode1-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, 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].  

> 首先是題意 'assume that each input would have **exactly** one solution' ,理解為 array 只有一組正確解。    ‘you may not use the same element twice’,應該理解為返回的indices不可以重複。   - 第一種思路,兩次迴圈: ```Python class Solution:     def twoSum(self, nums, target):         """         :type nums: List[int]         :type target: int         :rtype: List[int]         """         for i in range(len(nums)-1):             for j in range(i+1, len(nums)):                 if nums[i] + nums[j] == target:                     return [i, j] ``` ![res1](https://github.com/DaisyLoveU/Python-learning/blob/master/LeetCode/img/leetcode1_res_01.png)   **分析**:   兩次迴圈,時間複雜度 $O(n^{2})$ ,沒有額外的空間複雜度。

- 第二種思路, 構建hashtable,將第二次迴圈($ O(n) $)變成hashtable的查詢鍵值對($O(1)$);   hashtable的key和value分別為target-num和index of num

```Python class Solution:     def twoSum(self, nums, target):         """         :type nums: List[int]         :type target: int         :rtype: List[int]         """         hashtable = {}         for i,num in enumerate(nums):             if num in hashtable:                 return [hashtable[num], i]             else:                 hashtable[target-num] = i ``` ![res2](https://github.com/DaisyLoveU/Python-learning/blob/master/LeetCode/img/LeetCode1_res_2.png)   **分析**:    一次迴圈,時間複雜度$O(n)$, 構建了hashtable,有額外的$O(n)$空間複雜度。