41. leetcode題目講解(Python): 缺失的第一個正數(First Missing Positive)

題目如下:

解題思路:

題目要求時間複雜度爲O(n), 如果是對數組進行排序再查找,很難獲得比較好的效率。通過Python的 not in 判斷,可以更快的發現缺失目標。

參考代碼:

class Solution:
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in range(1, len(nums) + 2): # be careful the start and end
            if i not in nums:
                return i

源碼地址:
https://github.com/jediL/LeetCodeByPython

其它題目:[leetcode題目答案講解彙總(Python版 持續更新)]
(https://www.jianshu.com/p/60b5241ca28e)

ps:如果您有好的建議,歡迎交流 :-D,
也歡迎訪問我的個人博客 苔原帶 (www.tundrazone.com)

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