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;
}
};