Leetcode 1:two Sum

Source: Internet
Author: User

Leetcode 1:two Sum

Given an array of integers, find the numbers such that they add up to a specific target number.

The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.

You may assume this each input would has exactly one solution.

Input: numbers={2, 7, one, target=9
Output: index1=1, index2=2

Analysis

Use Python dict structure to solve it.

Store array to an dict. Let's assume X is a number in array. If both X and (Target-x) is in the dict, then they is what we is looking for.

Pay attention to an exception:

If target is twice x, we should take extra effort. Details is in codes explanation. Solution

Python Codes

Class solution (Object): Def twosum (self, Nums, target): "" ": Type Nums:list[int]: type target:in T:rtype:list[int] "" "L = [] D = {}" ": Store List value and index t o Dict:dict[value] = index + 1:if list Cantains Many same value and target is twice value, return the values            ' Indexes ' "" for index, X in Enumerate (nums): If x isn't in d:d[x] = index + 1 elif target = = 2 * x:l = [d[x], index+1] return L "": If (t        Arget-x) also exist in Dict and target are not twice value,: The result is indexes of X and (Target-x) "" "                For x in Nums:if ((target-x) in D) and target! = 2 * x:l = [d[x], D[target-x]] return L

Leetcode 1:two Sum

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.