LeetCode-top100-1. 两数之和-简单

###############################

"""
题目:
1. 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

"""

"""

分析
数组--数组中两个元素的和--目标值--返回两整数以及下标,

注意,
1.两个元素之和只有一个答案,
2.必须是两个元素之和,不能元素自己和自己相加,
3.只需要返回两个元素的下标

我想到了暴力求解:
循环每一个数字和其他数字相加,然后判断结果,
第一层循环,控制第一个数字,
第二层循环,控制第二个数字,始终是比上一个循环大1

这里面有很多的细节啊
1,range的用法
2,返回值的用法

"""

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n = len(nums)
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] + nums[j] == target:
                    return [i,j]

# 复杂度是O(n**2)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n = len(nums)
        for i in range(n):
            if target - nums[i] in nums:
                j = nums.index(target - nums[i])
                if i != j:
                    return [i,j]
                
# 复杂度降为O(n)

#################################

###############################

原文地址:https://www.cnblogs.com/andy0816/p/12407782.html