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
Related Topics:
Array
// OJ: https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int findSpecialInteger(vector<int>& A) {
int start = 0, N = A.size();
for (int i = 1; i < N; ) {
while (i < N && A[i] == A[start]) ++i;
if (i - start > N / 4) return A[start];
start = i;
}
return A[0];
}
};
// OJ: https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
int findSpecialInteger(vector<int>& A) {
int N = A.size(), t = N / 4;
for (int i = 0; i < N - t; ++i) {
if (A[i] == A[i + t]) return A[i];
}
return -1;
}
};
// OJ: https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(1)
class Solution {
public:
int findSpecialInteger(vector<int>& A) {
int N = A.size(), sizes[3] = { N / 4, N / 2, N * 3 / 4 };
for (int i : sizes) {
if (upper_bound(begin(A), end(A), A[i]) - lower_bound(begin(A), end(A), A[i]) > N / 4) return A[i];
}
return -1;
}
};