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

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

    How about: randomly select a small subset of K elements and look for duplicates (e.g. first 4, first 8, etc). If K == 4 then the probability of not getting at least 2 of the duplicates is 1/8. if K==8 then it goes to under 1%. If you find no duplicates repeat the process until you do. (assuming that the other elements are more randomly distributed, this would perform very poorly with, say, 49% of the array = "A", 51% of the array ="B").

    e.g.:

    findDuplicateCandidate: 
        select a fixed size subset.
        return the most common element in that subset
        if there is no element with more than 1 occurrence repeat.
        if there is more than 1 element with more than 1 occurrence call findDuplicate and choose the element the 2 calls have in common    
    

    This is a constant order operation (if the data set isn't bad) so then do a linear scan of the array in order(N) to verify.

提交回复
热议问题