描述
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
Note:
1 <= arr.length <= 10^4
0 <= arr[i] <= 10^5
解析
根据题意,找出出现次数多于 arr 长度的 25% 的元素。现对 arr 的元素进行计数得到字典 c ,然后遍历 c 找出出现次数满足题意的元素直接返回即可。
解答
class Solution(object):
def findSpecialInteger(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
N = len(arr)
t = N * 0.25
c = collections.Counter(arr)
for k,v in c.items():
if v > t:
return k
运行结果
Runtime: 88 ms, faster than 21.03% of Python online submissions for Element Appearing More Than 25% In Sorted Array.
Memory Usage: 15.6 MB, less than 7.54% of Python online submissions for Element Appearing More Than 25% In Sorted Array.
解析
因为肯定有答案,所以直接找出现次数最多的那个元素即可。
解答
class Solution(object):
def findSpecialInteger(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
return collections.Counter(arr).most_common(1)[0][0]
运行结果
Runtime: 76 ms, faster than 48.02% of Python online submissions for Element Appearing More Than 25% In Sorted Array.
Memory Usage: 15.5 MB, less than 11.11% of Python online submissions for Element Appearing More Than 25% In Sorted Array.
原题链接:leetcode.com/problems/el…
您的支持是我最大的动力