Count each contiguous run in the sorted array and return the first whose length exceeds one quarter of the array.
Complexity
O(n) time and O(1) space.
Find the value occurring in more than one quarter of a sorted array.
Count each contiguous run in the sorted array and return the first whose length exceeds one quarter of the array.
O(n) time and O(1) space.
package main
func findSpecialInteger(arr []int) int {
run := 1
for index := 1; index < len(arr); index++ {
if arr[index] == arr[index-1] {
run++
} else {
run = 1
}
if run*4 > len(arr) {
return arr[index]
}
}
return arr[0]
}
class Solution:
def findSpecialInteger(self, arr: list[int]) -> int:
run = 1
for index in range(1, len(arr)):
run = run + 1 if arr[index] == arr[index - 1] else 1
if run * 4 > len(arr): return arr[index]
return arr[0]
function findSpecialInteger(arr: number[]): number {
let run = 1;
for (let index = 1; index < arr.length; index += 1) { run = arr[index] === arr[index - 1] ? run + 1 : 1; if (run * 4 > arr.length) return arr[index]; }
return arr[0];
}