1. 程式人生 > >LeetCode #1 Two Sum

LeetCode #1 Two Sum

問題 code 後來 如果 默認 key-value 行存儲 方式 另一個

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

題意:給出一個數組和一個指定和,返回數組中兩個滿足相加等於指定和的數的下標(假設一定存在解);

想法:

1.最簡單粗暴的肯定就是進行兩層循環,以第一個數為基準遍歷剩余的數判斷是否和另一個數相加為指定和。復雜度為O(n^2)

2.覺得這樣的做法比較粗暴,效率不高,後來就考慮先將數排一遍序,初始兩個下標i、j,默認j在i後面,i從第一個數(下標為0)開始,j往後加,判斷相加符不符合,如果發現大了,說明後面的數肯定也不行了(畢竟已經排過序了),這時就讓j下標回退一步,讓i下標增加嘗試匹配。比如說1+6!=9、1+9!=9,但是3+6=9,如果j下標不回退有可能會錯過匹配。但是以上辦法有一個需要註意的地方,就是普通排序後會下標錯位,所以你要考慮如何保存下標,可以考慮用一個結構體把數和下標一起保存進行排序;

3.考慮了以上種種問題後,使用map這種key-value的方式進行存儲,Python中對應的是dict,思路就是一個個判斷下來,假設當前數為a,以target-a作為key去dict中取數,取到則說明能匹配,返回value和當前下標,如果不存在則更新,把值a作為key存入當前下標,這樣讀到a時就可以用target-a判斷有沒有存在該匹配了。

參考代碼:

 1 class Solution:
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
6 :rtype: List[int] 7 """ 8 lens = len(nums) 9 i = 0 10 map_item = {} 11 while i < lens: 12 if map_item.get(nums[i]) is not None : 13 return [nums.index(target-nums[i]),i] 14 else: 15 map_item[target-nums[i]]=nums[i] 16 i = i + 1

LeetCode #1 Two Sum