先看一篇大神寫(xiě)的文章:為什么要刷題
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