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

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

    int findLeader(int n, int* x){
        int leader = x[0], c = 1, i;
        for(i=1; i n/2) return leader;
            else return NULL;
        }
    }
    

    I'm not the author of this code, but this will work for your problem. The first part looks for a potential leader, the second checks if it appears more than n/2 times in the array.

提交回复
热议问题