Leetcode Python 1 review

Source: Internet
Author: User

Leetcode1

Given an array of integers and a target value, find the two numbers in the array and the target values.

You can assume that each input corresponds to only one answer, and that the same element cannot be reused.

Example:

Given nums = [2, 7, one, all], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 so return [0, 1]

The idea at the beginning of this topic is to set two non-repeating pointers, which are returned when the number of two digits is the target value.
As follows:
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
But this obvious readability is very high, easy to understand, the drawback is that time costs too much (N2)
The smaller the cost of the time, the greater the cost of space.
After watching someone else's code, get the following ideas:
With each value inside the Target-nums, save, O (n) space cost, see if the value exists in the original nuns, if present, then output these two values of index
The code is as follows:
ClassSolution(object):

DefTwosum(self, Nums, target):

"""

: Type Nums:list[int]

: Type Target:int

: Rtype:list[int]

"""

D = {}

ForI, numInchEnumerate (nums):

IfTarget-numInchD:

return [D[target-num], I]

D[num] = i
# for I, Num in enumerate (nums), called the Enumerate method, obtains a enumerate object, which can get the index and the object inside it with two parameters.


Leetcode Python 1 review

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.