[Lintcode Two-sum] Two number of sum (python, double pointer)

Source: Internet
Author: User
Tags lintcode

Title Link: http://www.lintcode.com/zh-cn/problem/two-sum/

Given an array of integers, find two numbers so that they are equal to a given number of target.

Backup a copy, and then sort. Make two pointers from left to right start scanning, each time to determine the sum of the two is not in line with test instructions, if small, then the left hand pointer to the right, the same as the pointer. The location is then found in the array of backups.

1 classSolution:2     """3 @param numbers:an array of integers4 @param target:target = numbers[index1] + numbers[index2]5 @return: [index1 + 1, Index2 + 1] (Index1 < INDEX2)6     """7     deftwosum (self, Numbers, target):8         #Write your code here9TMP = []Ten          forIinchnumbers: One tmp.append (i) ANumbers =sorted (Numbers) -A =0 -b = Len (numbers)-1 the          whileTrue: -             ifNumbers[a] + numbers[b] = =Target: -                  Break -             elifNumbers[a] + Numbers[b] <Target: +A + = 1 -             elifNumbers[a] + numbers[b] >Target: +B-= 1 AReta =Numbers[a] atRETB =Numbers[b] -A =-1 -b =-1 -          forIinchRange (0, Len (tmp)): -             ifTmp[i] = = Reta andA = =-1: -A =I in             elifTmp[i] = = Retb andb = =-1: -b =I to         ifA >B: +A = a ^b -b = a ^b theA = a ^b *         return[A+1, B+1]

[Lintcode Two-sum] Two number of sum (python, double pointer)

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.