You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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;
}
};
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;
}
};
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:
Example 2:
Constraints:
1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5
这道题给了一个有序数组,说是其中有一个数字出现了超过总个数的 25%,让找出这个数字。博主最开始做的时候,直接就用 HashMap 来统计每个数字出现的次数了,然后跟总长度的 1/4 比较,大于的话就直接返回该数字就好了,参见代码如下:
解法一:
上面的做法其实并没有利用到题目中给的有序这个条件,既然给定数组是有序的,说明了相同的数字一定是连在一起的,那么只要看固定区间的首位数字是否相等,相等的话就表示该区间内的所有的数字都是相等的。假如数组长度是n,则四分之一就是 n/4,只要判断 n/4 + 1 区间的首位数字是否相同就行了,即 arr[i] 和 arr[i + n/4] 是否相同,相同的话直接返回 arr[i] 即可,参见代码如下:
解法二:
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 打赏
---|---
The text was updated successfully, but these errors were encountered: