Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 1287. Element Appearing More Than 25% In Sorted Array #1287

Open
grandyang opened this issue May 30, 2019 · 0 comments
Open

[LeetCode] 1287. Element Appearing More Than 25% In Sorted Array #1287

grandyang opened this issue May 30, 2019 · 0 comments

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

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 同步地址:

#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 题目讲解汇总(持续更新中...)

喜欢请点赞,疼爱请打赏❤️~.~

微信打赏

|

Venmo 打赏


---|---

@grandyang grandyang changed the title [LeetCode] 1287. Missing Problem [LeetCode] 1287. Element Appearing More Than 25% In Sorted Array Apr 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant