Find 2 missing numbers in an array of integers with two missing values

前端 未结 12 916
梦谈多话
梦谈多话 2021-01-30 09:33

How do you do this? The values are unsorted but are of [1..n] Example array [3,1,2,5,7,8]. Answer: 4, 6

I saw this solution in

12条回答
  •  余生分开走
    2021-01-30 10:15

    Let x and y be the roots of a quadratic equation.

    • Sum of the roots, SUM = x + y
    • Product of the roots, PRODUCT = x * y

    If we know the sum and the product, we can reconstruct the quadratic equation as:

    z^2 - (SUM)z + (PRODUCT) = 0
    

    In the algorithm you mentioned, we find the sum and the product, and from that, we reconstruct the quadratic equation using the above formula.

    If you are interested in a detailed derivation, here is a reference. Read "Reconstruction of the quadratic equation from the sum and product of roots".

提交回复
热议问题