第一题:Two Sum

2017-11-06  本文已影响0人  码农小杨

先看一篇大神写的文章:为什么要刷题
http://selfboot.cn/2016/07/24/leetcode_guide_why/

内容:
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].

大值意思是存在一个数值列表,给定一个数值,判断列表内是否存在两个数是否相加等于给定的数值,若存在则返回对应的索引值。

参考答案:

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 

思路:

使用要判断的数与列表中的数相减,判断获得的差值是否存在列表中,如果存在则返回对应的序列号

知识点:

1. 返回列表的索引 enumerate()
2. 由值获得列表对应的索引 index()
3. 列表排序 sorted
上一篇下一篇

猜你喜欢

热点阅读