leetcode-1287-easy

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.

Example 1:

Input: arr = [1,2,2,6,6,6,6,7,10]
Output: 6
Example 2:

Input: arr = [1,1]
Output: 1
Constraints:

1 <= arr.length <= 104
0 <= arr[i] <= 105

思路一:由于给定的数组已经排好序,直接遍历,统计出现次数大于 25% 的数字,发现后直接返回。 大于 25% 的判断条件为 >= arr.length / 4 + 1;

public int findSpecialInteger(int[] arr) {
    int count = arr.length / 4 + 1;

    int pre = arr[0];
    int t = 1;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] == pre) {
            t++;
        } else {
            t = 1;
            pre = arr[i];
        }

        if (t >= count) break;
    }

    return pre;
}
posted @ 2022-11-07 19:49  iyiluo  阅读(21)  评论(0)    收藏  举报