Other algorithms and -042- (the double pointer Thought) of the two numbers S

Article Directory

Title Description

An incrementing input and a digital sorted array S, find the two numbers in the array, and so that they are exactly S, and if a plurality of digits equal to S, the product of the output of the minimum number of two.

Output Description:

Corresponding to each test case, the output of two numbers, the first small output.

analysis

  • Method a: double loop 暴力解法, and get all the two numbers, the time complexity is O ( n 2 n^2 )。
  • Method two: full use of the 数组递增有序features provided pointers to two 数组的两头, and the large, a large reduction in the pointer, and a small, small increases pointer equal a return pointer to meet two exit the loop. Similarly if the output of the two numbers 乘积最大, the initial 两指针指向中间两个数, to move to either side.

Code

# -*- coding:utf-8 -*-
class Solution:
    def FindNumbersWithSum(self, array, tsum):
        # write code here
        
        if not array:
            return []
        
        lowP = 0
        highP = len(array)-1
        
        while lowP<highP:
            if array[lowP]+array[highP]<tsum:
                lowP += 1
            elif array[lowP]+array[highP]>tsum:
                highP -= 1
            else:
                return array[lowP],array[highP]
        
        return []
Published 219 original articles · won praise 85 · Views 140,000 +

Guess you like

Origin blog.csdn.net/z_feng12489/article/details/103593280