Array of size n, with one element n/2 times

前端 未结 9 686
离开以前
离开以前 2021-02-04 12:41

Given an array of n integers, where one element appears more than n/2 times. We need to find that element in linear time and constant extra space.

YAAQ: Yet another arra

9条回答
  •  有刺的猬
    2021-02-04 13:17

    int n = A.Length;
                int[] L = new int[n + 1];
                L[0] = -1;
                for (int i = 0; i < n; i++)
                {
                    L[i + 1] = A[i];
                }
                int count = 0;
                int pos = (n + 1) / 2;
                int candidate = L[pos];
                for (int i = 1; i <= n; i++)
                {
                    if (L[i] == candidate && L[pos++] == candidate)
                        return candidate;
                }
                if (count > pos)
                    return candidate;
                return (-1);
    

提交回复
热议问题