劍指offer 面試39題


面試39題:

題目:數組中出現次數超過一半的數字

題:數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度為9的數組{1,2,3,2,2,2,5,4,2}。由於數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。

解題思路:根據數組特點找出時間復雜度為O(n)的算法。因為該數字出現次數比其他所有數字出現的次數之和還要多,所有要找的數字肯定是最后一次把次數設為1時對應的數字。

解題代碼一:

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        #檢查數組是否為無效的輸入
        if not numbers or len(numbers)<=0:
            return 0
        
        #若存在則該數出現次數比其他所有數字出現次數之和還要多,則要找的數字肯定是最后一次把次數設為1時對應的數字
        res=numbers[0]
        times=1
        for i in range(1,len(numbers)):
            if times==0:
                res=numbers[i]
                times=1
            elif numbers[i]==res:
                times+=1
            else:
                times-=1
        #檢查其次數是否大於數組的一半,若不是則返回0
        def CheckMoreThanHalf(numbers,number):
            length=len(numbers)
            times=0
            for i in range(length):
                if numbers[i]==number:
                    times+=1
            if times*2<=length:
                return False
            return True
        if CheckMoreThanHalf(numbers,res):
            return res
        return 0

解題代碼二:更簡潔。

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        #檢查數組是否為無效的輸入
        if not numbers or len(numbers)<=0:
            return 0
        
        #若存在則該數出現次數比其他所有數字出現次數之和還要多,則要找的數字肯定是最后一次把次數設為1時對應的數字
        res=numbers[0]
        times=1
        for i in range(1,len(numbers)):
            if times==0:
                res=numbers[i]
                times=1
            elif numbers[i]==res:
                times+=1
            else:
                times-=1
        
        sum=0
        for j in numbers:
            if j==res:
                sum+=1
        return res if sum*2>len(numbers) else 0

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM