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

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

提交回复
热议问题