第一題:Two Sum

先看一篇大神寫的文章:為什么要刷題
http://selfboot.cn/2016/07/24/leetcode_guide_why/

內(nèi)容:
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].

大值意思是存在一個(gè)數(shù)值列表,給定一個(gè)數(shù)值,判斷列表內(nèi)是否存在兩個(gè)數(shù)是否相加等于給定的數(shù)值,若存在則返回對(duì)應(yīng)的索引值。

參考答案:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i, num in enumerate(nums):
            other = target - num 
            try:
                position = nums.index(other)
                if position != i:
                    return sorted([i,position])
            except ValueError:
                pass 

思路:

使用要判斷的數(shù)與列表中的數(shù)相減,判斷獲得的差值是否存在列表中,如果存在則返回對(duì)應(yīng)的序列號(hào)

知識(shí)點(diǎn):

1. 返回列表的索引 enumerate()
2. 由值獲得列表對(duì)應(yīng)的索引 index()
3. 列表排序 sorted
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容