finding triangulars from array

后端 未结 5 778
一向
一向 2021-01-07 12:58

zero-indexed array A consisting of N integers is given. A triplet (P, Q, R) is triangular if and

A[P] + A[Q] > A[R], 
A[Q] + A[R] > A[P], 
A[R] + A[P         


        
5条回答
  •  攒了一身酷
    2021-01-07 13:57

    There are many in-place sorts; use one of them to sort the array - say comb sort for smaller ones (time complexity O(N^2)) or heap sort (complexity O(N log(N)).

    Once you have sorted array, problem should be whether there is a set of 3 numbers where A[X] > (A[X-1] + A[X+1]) / 2 i.e. middle number is greater than average of preceding & succeeding numbers (sadly this is a guess, I don't have a real basis - if its incorrect I hope someone corrects me, but there should be some good way to redefine the 'triangle' requirement to be more easily checked).

    Now you just have an O(1) iteration over the sorted array to check whether the condition is true, hence overall complexity will be that of the sorting algorithm (best case N logN)

提交回复
热议问题