top100-1 two numbers - simple

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

"""
topic:
1. The sum of two numbers

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.
You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Example:
Given nums = [2, 7, 11, 15], target = 9
Because nums [0] + nums [1] = 2 + 7 = 9
Is returned [0, 1]

"""

"""

analysis
Array - and two elements in the array - target - Returns the integer and two subscripts,

note,
1. The sum of the two elements is only one answer,
2. Must be the sum of two elements, the elements themselves and their sum can not,
3. only need to return the subscript two elements

I thought of solving violence:
Each cycle numbers, and other numbers are added, then the determination result,
The first layer loop controls the first number,
A second layer loop, controlling the second number is always a large than 1 cycle

There are a lot of details ah
1, range usage
2, the return value of usage

"""

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]

# Complexity is 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]
                
# Complexity is reduced to O (n)

 

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

 

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

Guess you like

Origin www.cnblogs.com/andy0816/p/12407782.html