題目:
這是一道Leetcode
上等級爲easy
的題目:
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].
解決思路:
從列表中依次取出數據,每次利用目標數據減去取出數據獲得它需要的另一半,再拿得到的結果判斷剩餘的列表中是否存在(由於是依次判斷的,確保前面不會有可用數據,可以大膽切割),存在則獲取兩個數據的位置。
python3
實現:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l = len(nums)
for i in range(l):
temp = target - nums[i]
surplus = nums[i+1:]
if temp in surplus:
j = surplus.index(temp) + i + 1 # Make up the missing index after sharding (Has two 0 indexes)
return [i, j]
# The following code works the same way, but a little faster, which is probably negligible
class SolutionAnother:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) >= 2:
i = -1
for each in nums:
i += 1 # Calculate current position
temp = target - each
surplus = nums[i+1:]
if temp in surplus:
j = surplus.index(temp) + i + 1 # Make up the missing index after sharding (Has two 0 indexes)
return [i, j]
結果分析:
這種實現方法,python
裏面列表提供了自動檢測元素存在和位置獲取的方法,是有捷徑可走的,別的語言用這種思路是否方便就不是很瞭解了。至於運行時間這個問題,這裏一共是29個測試用例的時間,所以顯得比較長。另外在LeetCode
上還有很多別的優秀方法,比如有一個和上述方法思路完全一致的解法鏈接,但是他用try-except
來處理列表數據的查找和定位部分,代碼看起來很簡潔。這裏僅記錄了自己的實現,歡迎指正和探討。