牛客網在線編程專題《劍指offer-面試題40》數組中只出現一次的數字

我的個人微信公衆號:Microstrong

微信公衆號ID:MicrostrongAI

微信公衆號介紹:Microstrong(小強)同學主要研究機器學習、深度學習、計算機視覺、智能對話系統相關內容,分享在學習過程中的讀書筆記!期待您的關注,歡迎一起學習交流進步!

知乎主頁:https://www.zhihu.com/people/MicrostrongAI/activities

Github:https://github.com/Microstrong0305

個人博客:https://blog.csdn.net/program_developer

 題目鏈接:

https://www.nowcoder.com/practice/e02fdb54d7524710a7d664d082bb7811?tpId=13&tqId=11193&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

題目描述:

 解題思路:

(1)以空間複雜度換時間複雜度

空間複雜度O(n),時間複雜度O(n)

已經AC的代碼:

# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出現一次的兩個數字
    def FindNumsAppearOnce(self, array):
        # write code here
        num_dic = {}
        result_list = []
        for item in array:
            if item in num_dic.keys():
                num_dic[item] = num_dic[item] + 1
            else:
                num_dic[item] = 1

        for item, count in num_dic.items():
            if count == 1:
                result_list.append(item)

        return result_list


if __name__ == "__main__":
    input_array = [2, 4, 3, 6, 3, 2, 5, 5]
    sol = Solution()
    print(sol.FindNumsAppearOnce(input_array))

(2)利用Python中list.count()函數,時間複雜度爲o(n)

# -*- coding:utf-8 -*-
class Solution:
    # 返回[a,b] 其中ab是出現一次的兩個數字
    def FindNumsAppearOnce(self, array):
        # write code here
        result_list = []
        for item in array:
            count = array.count(item)
            if count == 1:
                result_list.append(item)

        return result_list

 

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