Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time.

Return that integer.

 

Example 1:

Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
 

Constraints:

1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5

很直接,计数即可。

class ElementAppearingMoreThan25PercentInSortedArray : public Solution {
public:
    void Exec() {

    }
    int findSpecialInteger(vector<int>& arr) {
        int line = arr.size() / 4;
        int prev = arr[0];
        int count = 1;

        for (int i = 1; i < arr.size(); i++) {
            if (arr[i] == prev) {
                count++;
            } else {
                if (count > line) {
                    return prev;
                }
                prev = arr[i];
                count = 1;
            }
        }
        if (count > line) {
            return prev;
        }
        return 0;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day