[LeetCode] Element Appearing More Than 25% In Sorted Array

1287. Element Appearing More Than 25% In Sorted Array

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int findSpecialInteger(vector<int>& A) {
int n = A.size(), now = -1, cnt = 0;
for(auto& x : A) {
if(x == now) cnt += 1;
else cnt = 1, now = x;
if(cnt * 4 > n) return x;
}
return 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/11/PS/LeetCode/element-appearing-more-than-25-in-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.