[LeetCode] 1287. Element Appearing More Than 25% In Sorted Array 有序数组中出现次数超过25%的元素


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 <= 10^4
  • 0 <= arr[i] <= 10^5

这道题给了一个有序数组,说是其中有一个数字出现了超过总个数的 25%,让找出这个数字。博主最开始做的时候,直接就用 HashMap 来统计每个数字出现的次数了,然后跟总长度的 1/4 比较,大于的话就直接返回该数字就好了,参见代码如下:


解法一:

class Solution {
public:
    int findSpecialInteger(vector<int>& arr) {
        int n = arr.size(), target = n / 4;
        unordered_map<int, int> numCnt;
        for (int num : arr) {
            if (++numCnt[num] > target) return num;
        }
        return -1;
    }
};

上面的做法其实并没有利用到题目中给的有序这个条件,既然给定数组是有序的,说明了相同的数字一定是连在一起的,那么只要看固定区间的首位数字是否相等,相等的话就表示该区间内的所有的数字都是相等的。假如数组长度是n,则四分之一就是 n/4,只要判断 n/4 + 1 区间的首位数字是否相同就行了,即 arr[i] 和 arr[i + n/4] 是否相同,相同的话直接返回 arr[i] 即可,参见代码如下:


解法二:

class Solution {
public:
    int findSpecialInteger(vector<int>& arr) {
        int n = arr.size(), t = n / 4;
        for (int i = 0; i < n - t; ++i) {
            if (arr[i] == arr[i + t]) return arr[i];
        }
        return -1;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1287


参考资料:

https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/

https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/discuss/1399162/4-Minute-Read-Mimicking-an-Interview

https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/discuss/451249/Simple-Java-Solution-O(n)-time-O(1)-space


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2022-03-20 08:31  Grandyang  阅读(345)  评论(0编辑  收藏  举报
Fork me on GitHub