码迷,mamicode.com
首页 > 其他好文 > 详细

难度等级简单 -1

时间:2019-06-20 17:23:38      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:sum   solution   turn   get   target   elf   整数   给定一个整数数组   list   

‘‘‘
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个
 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的yuansu
‘‘‘
class Solution(object):
    def two_sum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i,num in enumerate(nums):
            value = target - num
            if value in nums[i+1:]:
                return [i, nums[i+1:].index(value)+i+1]
        return None

自己错误的解法,忽视去掉一个元素后,其相应的下标也变了,代码如下

class Solution(object):
    def two_sum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for num1 in nums:
            result = []
            num1_i = nums.index(num1)
            result.append(num1_i)
            nums.remove(num1)
            for num2 in nums:
                if num1 +  num2 == target:
                    num2_i = nums.index(num2)
                    result.append(num2_i)
                    return result
        return None

 

难度等级简单 -1

标签:sum   solution   turn   get   target   elf   整数   给定一个整数数组   list   

原文地址:https://www.cnblogs.com/jj1106/p/11059717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!