当前位置: 移动技术网 > IT编程>脚本编程>Python > [LeetCode][Python]刷题记录 1. 两数之和

[LeetCode][Python]刷题记录 1. 两数之和

2018年09月03日  | 移动技术网IT编程  | 我要评论

铿锵玫瑰之风行天下,aqounsenton,巨蛤

第一次做发现很多小细节以前都没注意过,感觉还是蛮头疼的。

题目:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

根据题目要求【你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。】

所以我们的思路就有了,只要每次循环只遍历后面的就可以啦,这样结果就不会重复惹。

上代码

class solution:
    def twosum(self, nums, target):
        """
        :type nums: list[int]
        :type target: int
        :rtype: list[int]
        """
        for i in nums:
           for j in range(nums.index(i) + 1, len(nums)):
               if i + nums[j] == target:
                    list = [nums.index(i),j]
                    return(list)
nums = [2, 7, 11, 15]
target = 9
a = solution()
print(a.twosum(nums,target))

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网