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

前端 未结 9 688
离开以前
离开以前 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:16

    Well you can do an inplace radix sort as described here[pdf] this takes no extra space and linear time. then you can make a single pass counting consecutive elements and terminating at count > n/2.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-02-04 13:21

    My first thought (not sufficient) would be to:

    • Sort the array in place
    • Return the middle element

    But that would be O(n log n), as would any recursive solution.

    If you can destructively modify the array (and various other conditions apply) you could do a pass replacing elements with their counts or something. Do you know anything else about the array, and are you allowed to modify it?

    Edit Leaving my answer here for posterity, but I think Skeet's got it.

    0 讨论(0)
提交回复
热议问题