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

前端 未结 8 1029
抹茶落季
抹茶落季 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:15

    I have a solution(actually 2 solutions ;-)). Writing it in python:

    def find_count(input_list, min, max):
        count = 0
        range_diff = max - min
        for i in range(len(input_list)):
            if input_list[i]*2 >= min and input_list[i]*2 <= max:
                count += 1
            for j in range(i+1, len(input_list)):
                input_sum = input_list[i] + input_list[j]
                if input_sum >= min and input_sum <= max:
                    count += 2
    

    This will run nCr(n combinations) times to the max and gives you the required count. This will be better than sorting the list and then finding the pairs in a range. If the number of elements that fail the combination is greater as well as all the numbers are positive integers, we can improve the result a little better by adding a condition that checks the elements for,

    • Numbers that do not fall under the range even with the addition of the max value
    • Numbers that are greater than the maximum number of the range.

    Something like this:

    # list_maximum is the maximum number of the list (i.e) max(input_list), if already known
    def find_count(input_list, min, max, list_maximum):
        count = 0
        range_diff = max - min
        for i in range(len(input_list)):
            if input_list[i] > max or input_list[i] + list_maximum < min:
                continue
            if input_list[i]*2 >= min and input_list[i]*2 <= max:
                count += 1
            for j in range(i+1, len(input_list)):
                input_sum = input_list[i] + input_list[j]
                if input_sum >= min and input_sum <= max:
                    count += 2
    

    I will also be happy to learn any better solution than this :-) If i come across one, I will update this answer.

提交回复
热议问题