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

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

    This is what I thought initially.

    I made an attempt to keep the invariant "one element appears more than n/2 times", while reducing the problem set.

    Lets start comparing a[i], a[i+1]. If they're equal we compare a[i+i], a[i+2]. If not, we remove both a[i], a[i+1] from the array. We repeat this until i>=(current size)/2. At this point we'll have 'THE' element occupying the first (current size)/2 positions. This would maintain the invariant.

    The only caveat is that we assume that the array is in a linked list [for it to give a O(n) complexity.]

    What say folks?

    -bhupi

提交回复
热议问题