LeetCode twoSum Python

LeetCode twoSum Python

这个题目有两个要求:每个输入只有一个solution,而且相同的元素不能使用两次。

解题思路:

第一种,可以使用两个for循环来遍历这个list,从前开始遍历用i表示,从后开始遍历用j表示,并且满足条件i<j,如果i对应的元素和j对应的元素之和相加为target即返回i和j。

第二种就是使用if来判断target-nums[i]之后的值是否在列表中,这个需要注意target-nums[i]的值不能是本身,所以需要加一个if判断一下。代码如下:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        length = len(nums)
        for i in range(length):
            com = target - nums[i]
            if com in nums:
                if i<nums.index(com):
                    print([i, nums.index(com)])


if __name__ == '__main__':

        nums =[3,2,4]
        a=Solution()
        a.twoSum(nums,5)
但是我的代码在LeetCode上面运行之后的结果如下:

LeetCode twoSum Python

我不知道为什么打印了两遍,而且我看了好多大家的博客都需要用dict,我不是很理解,我这个代码在pycharm中运行是正确的,哪位大神看了能给我讲解一下,谢谢了老铁!