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

前端 未结 12 1037
梦谈多话
梦谈多话 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条回答
  •  Happy的楠姐
    2021-01-30 10:24

    #include 
    #include 
    
    /*
        the sum should be 1+...+n = n(n+1)/2
        the sum of squares should be 1^2+...+n^2 = n(n+1)(2n+1)/6.
    */
    
    void find_missing_2_numbers(int *arr, int n);
    
    int main()
    {
        int arr[] = {3,7,1,6,8,5};
    
        find_missing_2_numbers(arr, 8);
    
        return 0;
    }
    
    void find_missing_2_numbers(int *arr, int n)
    {
    
        int i, size, a, b, sum, sum_of_sqr, a_p_b, as_p_bs, a_i_b, a_m_b;
        size = n - 2;
    
        sum = 0;
        sum_of_sqr = 0;
        for (i = 0; i < size; i++)
        {
            sum += arr[i];
            sum_of_sqr += (arr[i] * arr[i]);
        }
    
        a_p_b = (n*(n+1))/2 - sum;
        as_p_bs = (n*(n+1)*(2 * n + 1))/6 - sum_of_sqr;
        a_i_b = ((a_p_b * a_p_b) - as_p_bs ) / 2;
        a_m_b = (int) sqrt((a_p_b * a_p_b) - 4 * a_i_b);
        a = (a_p_b + a_m_b) / 2;
        b = a_p_b - a;
    
        printf ("A: %d, B: %d\n", a, b);
    }
    

提交回复
热议问题