How to find all ordered pairs of elements in array of integers whose sum lies in a given range of value

前端 未结 8 1045
抹茶落季
抹茶落季 2021-02-05 21:58

Given an array of integers find the number of all ordered pairs of elements in the array whose sum lies in a given range [a,b]

Here is an O(n^2) solution for the same <

8条回答
  •  广开言路
    2021-02-05 22:13

    Rather than using the relational operators, we can simply check if the sum of array elements i and j are in the specified range.

    def get_numOfPairs(array, start, stop):
        num_of_pairs = 0
        array_length = len(array)
    
        for i in range(array_length):
            for j in range(i+1, array_length):
                if sum([array[i], array[j]]) in range(start, stop):
                    num_of_pairs += 1
    
        return num_of_pairs
    

提交回复
热议问题