Press "Enter" to skip to content

花花酱 LeetCode 1287. 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:

Constraints:

  • 1 <= arr.length <= 10^4
  • 0 <= arr[i] <= 10^5

Solution 1: Linear Scan

if arr[i] == arr[i + len/4] => arr[i] is the special integer.

Time complexity: O(n)
Space complexity: O(1)

C++

Solution 2: Binary Search

The answer must be one of (s[0], s[l/4], s[l/2], s[l*3/4])
Using binary search to find the range of each number, the one has more than 1/4 of total elements is the answer.

Time complexity: O(logn)
Space complexity: O(1)

C++

请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website
您可以通过在亚马逊上购物(任意商品)来支持我们

Paypal
Venmo
huahualeetcode
微信打赏

Be First to Comment

Leave a Reply