【線段樹】A000_LC_子數組中佔絕大多數的元素(摩爾投票 / 線段樹)

一、Problem

Implementing the class MajorityChecker, which has the following API:

MajorityChecker(int[] arr) constructs an instance of MajorityChecker with the given array arr;
int query(int left, int right, int threshold) has arguments such that:
0 <= left <= right < arr.length representing a subarray of arr;
2 * threshold > right - left + 1, ie. the threshold is always a strict majority of the length of the subarray
Each query(…) returns the element in arr[left], arr[left+1], …, arr[right] that occurs at least threshold times, or -1 if no such element exists.

MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2

Constraints:

1 <= arr.length <= 20000
1 <= arr[i] <= 20000
For each query, 0 <= left <= right < len(arr)
For each query, 2 * threshold > right - left + 1
The number of queries is at most 10000

二、Solution

方法一:摩爾投票

竟然不會 TLE,104+5=910^{4+5=9}

class MajorityChecker {
    int a[];
    public MajorityChecker(int[] arr) {
        a = arr;
    }
    
    public int query(int left, int right, int thre) {
        int v = a[left], c = 1;
        for (int i = left+1; i < right; i++) {
            if (v == a[i])
                c++;
            else {
                c--;
                if (c == 0)
                    v = a[i+1];
            }
        }
        int cnt = 0;
        for (int i = left; i <= right; i++) if (v == a[i])
            cnt++;
        return cnt >= thre ? v : -1;
    }
}

複雜度分析

  • 時間複雜度:O(q×n)O(q × n)
  • 空間複雜度:O(1)O(1)

方法二:線段樹

代辦


複雜度分析

  • 時間複雜度:O()O()
  • 空間複雜度:O()O()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章