LeetCode1——两数之和(python)

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。
方法1:暴力运算

class Solutions(object):
    def two_sum(self, nums, target):
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[j] == target - nums[i]:
                    return i, j
                pass
            pass
        pass

方法2:

def twoSum(nums, target):
    lens = len(nums)
    j = -1
    for i in range(lens):
        if (target - nums[i]) in nums:
            if (nums.count(target - nums[i]) == 1) & (
                    target - nums[i] == nums[i]):  # 如果num2=num1,且nums中只出现了一次,说明找到是num1本身。
                continue
            else:
                j = nums.index(target - nums[i], i + 1)  # index(x,i+1)是从num1后的序列后找num2
                break
    if j > 0:
        return [i, j]
    else:
        return []

猜你喜欢

转载自blog.csdn.net/weixin_51871724/article/details/121174396