LeetCode.001.Two Sum, leetcode.001.two

Source: Internet
Author: User

LeetCode.001.Two Sum, leetcode.001.two

Address: https://leetcode.com/problems/two-sum/

Question:

Given an array and a target, if the sum of two numbers in the array is exactly the same as the target, their subscript is returned.

Question:

There are a lot of ideas. You can simply do this by sorting them first, then traversing each number, and searching for the other in binary mode. Because python comes with a dictionary tree (dist ), this method is more convenient:
Create a table based on d = {value: subscript}, traverse each number, search for another one, and return the subscript of these two numbers.

Code:

1 class Solution (object): 2 def twoSum (self, nums, target): 3 "" 4: type nums: List [int] 5: type target: int 6: rtype: List [int] 7 "" 8 lena = len (nums) 9 d = {0x3fffffff: 0x3fffffff} 10 for I in range (lena ): 11 d [nums [I] = i12 13 for I in range (lena): 14 temp = target-nums [I] 15 if temp in d: 16 if d [temp]! = I: 17 return [I, d [temp]

 

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.