LeetCode:1287. Element Appearing More Than 25% In Sorted Array - Python

1287. 有序數組中出現次數超過25%的元素

問題描述:

給你一個非遞減有序 整數數組,已知這個數組中恰好有一個整數,它的出現次數超過數組元素總數的25%

請你找到並返回這個整數

示例 :

輸入:arr = [1,2,2,6,6,6,6,7,10]
輸出:6

問題分析:

先看問題,題目要求(1)遞增的有序的數組;(2)恰好有一個整數出現的次數超過25%。
解決思路:
方法一:從頭掃描數組,並記錄第一個超過25%的整數,則立即返回,即可。
方法二:投機取巧,直接使用Python的 collections 庫,直接返回即可。

Python3實現:

方法一:
class Solution:
    def findSpecialInteger(self, arr):
        if arr == []:
            return 0
        curr = None
        cnt = 0
        for x in arr:
            if x == curr:
                cnt += 1
            else:
                curr = x
                cnt = 1
            if cnt > len(arr) / 4:
                return curr


if __name__ == '__main__':
    solu = Solution()
    arr = [1, 2, 2, 6, 6, 6, 6, 7, 10]
    print(solu.findSpecialInteger(arr))
方法二:
from collections import Counter


class Solution:
    def findSpecialInteger(self, arr):
        return Counter(arr).most_common(1)[0][0]

if __name__ == '__main__':
    solu = Solution()
    arr = [1, 2, 2, 6, 6, 6, 6, 7, 10]
    print(solu.findSpecialInteger(arr))

聲明: 總結學習,有問題或不當之處,可以批評指正哦,謝謝。

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章