Leetcode1-two Sums

Source: Internet
Author: User

Topic https://leetcode.com/problems/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, A, target=9
Output:index1=1, index2=2

Ideas

First consider the time Complexity O (n^2) loop traversal, Leetcode can not endure.

The second scenario is O (N), when iterating through an array, the value is key, the index is a dictionary of value, and then each time the target value minus the current value from the dictionary gets index,index less than I, the description exists in the dictionary.

Code O (n^2)

classSolution1:#@param {integer[]} nums    #@param {integer} target    #@return {integer[]}    deftwosum (self, Nums, target): RLT= []        if  notNums:returnRLT forIinchRange (len (nums)): forJinchRange (Len (nums[i+1:])):                ifNums[i] + nums[i+j] = =target:rlt.append (i) rlt.append (i+j)returnRlt

Code O (N)
classSolution:#@param {integer[]} nums    #@param {integer} target    #@return {integer[]}    deftwosum (self, Nums, target): RLT= []        if  notNums:returnRLT num_dict= {}         forIinchRange (len (nums)):ifNums[i] not inchNum_dict:num_dict[nums[i]]=IPrintNums[i],i J= Num_dict.get (Target-nums[i], 1)            ifJ < I andJ >-1: Rlt.append (J+1) rlt.append (i+1)                returnRLTreturnRlt

Refer to Address 1. http://blog.csdn.net/jiadebin890724/article/details/23305449

Leetcode1-two Sums

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.