finding triplets

后端 未结 2 688
轻奢々
轻奢々 2021-02-02 17:00

I know this type of question has been posted before, but i want to discuss something new.So, i am posting it.

Given an unsorted array of integers, find all triplets tha

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 17:13

    Another possibility (who can fathom the mind of an interviewer?) would be to rewrite the equation as:

     x^2 + y^2 = z^2
     x^2 = z^2 - y^2 = (z-y)(z+y)
    

    If we knew the prime factorisation of x^2 then we could simply iterate through all possible factorisations into a pair of numbers p,q (with p < q) and compute

     x^2 = p.q = (z-y)(z+y)
     p+q = (z-y)+(z+y) = 2z
     q-p = (z+y)-(z-y) = 2y
     z = (p+q)/2
     y = (q-p)/2
    

    So given a factorisation x^2=p.q we can work out the z and y values. By putting all the integer values into a set we can then check each possible answer in time O(1) (per check) by looking to see if those z,y values are in the array (taking care that negative values are also detected).

    Wikipedia says that a randomly chosen integer has about log(n) divisors so this should take about n.log(n) assuming you can do the factorisation fast enough (e.g. if you knew all the integers were under a million you could precompute an array of the smallest factor for each integer).

提交回复
热议问题