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.
Since the array is sorted and there is exactly one element that appears more than 25% of the time, it must appear at least at one of the positions: n//4, n//2, or 3n//4. We can check these positions and count the occurrences of the candidate using binary search or a simple scan.
classSolution {
public:int findSpecialInteger(vector<int>& arr) {
int n = arr.size(), k = n /4;
for (int i : {k, 2* k, 3* k}) {
if (i + k < n && arr[i] == arr[i + k]) return arr[i];
}
return arr[0];
}
};
classSolution {
publicintfindSpecialInteger(int[] arr) {
int n = arr.length, k = n / 4;
for (int i : newint[]{k, 2 * k, 3 * k}) {
if (i + k < n && arr[i]== arr[i + k]) return arr[i];
}
return arr[0];
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funfindSpecialInteger(arr: IntArray): Int {
val n = arr.size
val k = n / 4for (i in listOf(k, 2 * k, 3 * k)) {
if (i + k < n && arr[i] == arr[i + k]) return arr[i]
}
return arr[0]
}
}
1
2
3
4
5
6
7
8
classSolution:
deffindSpecialInteger(self, arr: list[int]) -> int:
n = len(arr)
k = n //4for i in [k, 2* k, 3* k]:
if i + k < n and arr[i] == arr[i + k]:
return arr[i]
return arr[0]
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnfind_special_integer(arr: Vec<i32>) -> i32 {
let n = arr.len();
let k = n /4;
for&i in&[k, 2* k, 3* k] {
if i + k < n && arr[i] == arr[i + k] {
return arr[i];
}
}
arr[0]
}
}