find pair of numbers in array that add to given sum

前端 未结 19 2142
萌比男神i
萌比男神i 2020-11-30 20:17

Question: Given an unsorted array of positive integers, is it possible to find a pair of integers from that array that sum up to a given sum?

Constraints: This shou

19条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 20:33

    Here is a solution in python:

    a = [9, 8, 9, 2, 15, 11, 21, 8, 9, 2, 2, 8, 9, 2, 15, 11, 21, 8, 9, 2, 9, 8, 9, 2, 15, 11, 21, 8, 9, 2, 2, 8, 9, 2, 15, 11, 2, 8, 9, 2, 2, 8,
         9, 2, 15, 11, 21, 8, 9, 12, 2, 8, 9, 2, 15, 11, 21, 7, 9, 2, 23, 8, 9, 2, 15, 11, 21, 8, 9, 2, 2, 12, 9, 2, 15, 11, 21, 8, 9, 2, 2,
         8, 9, 2, 15, 11, 21, 8, 9, 2, 2, 8, 9, 2, 15, 11, 21, 8, 9, 2, 2, 8, 9, 2, 15, 11, 21, 8, 9, 2, 2, 7.12, 9, 2, 15, 11, 21, 8, 9, 2, 2, 8, 9,
         2, 15, 11, 21, 8, 9, 2, 2, 8, 9, 2, 15, 11, 21, 8, 9, 2, 2, 8, 9, 2, 15, 11, 21, 8, 9, 2, 2, 8, 9, 2, 15, 11, 21, 8, 0.87, 78]
    i = 0
    j = len(a) - 1
    my_sum = 8
    finded_numbers = ()
    iterations = 0
    while(OK):
        iterations += 1
        if (i < j):
            i += 1
        if (i == j):
            if (i == 0):
                OK = False
                break
            i = 0
            j -= 1
        if (a[i] + a[j] == my_sum):
            finded_numbers = (a[i], a[j]) 
            OK = False
    print finded_numbers
    print iterations
    

提交回复
热议问题