Quickly locate whether the sum of the two numbers in the sorted array is X

Source: Internet
Author: User

Problem description: The sorted (ascending) array is a [n] to find out whether there are two numbers in the array and the given X


Solution:

(1) define the pointer P = A [0], r = A [n-1]

(2) determine whether P + R is equal to X:

If the value is equal

If P + r> X, r moves forward to a grid.

If P + r <X, p moves one bit back.

(3) Repeat (2) until it is found or P> r stops


I used python to simulate why I used python. Today I see a sentence: Life is too short, use python!

 
Import randomr = int (raw_input ("input the sum x:") n = int (raw_input ("input the length N of the arry :")) arry = [] For I in range (1, n + 1): S = random. randint (1,100) Arry. append (s) Arry. sort () print arryprint ''x = 0y = n-1flag = truetimes = 0 while x <= Y: If arry [x] + arry [y] = R: print 'Arry [', X,']: ', arry [X],' + arry [', Y,']: ', arry [Y],' = ', r, ', Times =', times flag = false break Elif arry [x] + arry [y]> r: Y = Y-1 times = times + 1 else: X = x + 1 times = times + 1if flag: Print 'no two num \'s sum is the ', R

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.