Leetcode-1-the Sum

Source: Internet
Author: User

Given an array of integers, return indices of the both numbers such that they add-to a specific target.

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

Example:

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

In short, find two numbers within a given array, making two numbers and for a given target

Ideas:

Iterates through the given array, using a hash table to hold the values that have been traversed, key is the value in Nums, and value is its position index.

For the currently traversed Nums[i], look for the existence of target-nums[i in the hash table, or, if present, return both indexes, otherwise (key=nums[i],value=i) into the hash table and continue traversing

Time complexity: O (N)

The Python code is as follows, AC:

1 classsolution (object):2     deftwosum (self, Nums, target):3         """4 : Type Nums:list[int]5 : Type Target:int6 : Rtype:list[int]7         """8Dictmap = {}9          forIndex, valueinchEnumerate (nums):Ten             ifTarget-valueinchDictmap: One                 return[Dictmap[target-value], index] ADictmap[value] = Index

Submit Result:

Leetcode-1-the 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.