Codility-EquiLeader

本文介绍了一个算法挑战,即在一个整数数组中找到所有EquiLeader的个数。EquiLeader是指一个索引,该索引将数组分成两部分,且这两部分具有相同的主导元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Task description

A non-empty zero-indexed array A consisting of N integers is given.

The leader of this array is the value that occurs in more than half of the elements of A.

An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.

For example, given array A such that:

    A[0] = 4
    A[1] = 3
    A[2] = 4
    A[3] = 4
    A[4] = 4
    A[5] = 2

we can find two equi leaders:

  • 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
  • 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4.

The goal is to count the number of equi leaders. Write a function:

int solution(vector<int> &A);

that, given a non-empty zero-indexed array A consisting of N integers, returns the number of equi leaders.

For example, given:

    A[0] = 4
    A[1] = 3
    A[2] = 4
    A[3] = 4
    A[4] = 4
    A[5] = 2

the function should return 2, as explained above.

Assume that:

  • N is an integer within the range [1..100,000];
  • each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

此题可算作Dominator的扩展题,意思是选定一个下标,将一个数组分为左右两个子数组,使得两个子数组都有相同的leader,则称此下标为EquiLeader,要求返回给定数组中EquiLeader的个数n。事实上,若一个数同时是左子数组的leader,它必然也是整个数组的leader。
因此,此题也是需要先找出序列中的leader,记录其出现的次数。然后再遍历整个数组,枚举分割点,记录下左子数组leader出现的次数s,看s与n-s是否能使得leader在左右子数组中仍为leader。
// you can use includes, for example:
// #include 

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(vector &A) {
    // write your code in C++11
    int size = 1;
    int value = A[0];
    for(unsigned int i=1;i(k+1)/2)&&((A.size()-k-1)/2<(cnt-leftCnt)))
        res++;
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值