본문 바로가기
LeetCode/Problems

LeetCode 41. First Missing Positive

by 벤진[Benzene] 2020. 6. 18.

Problem:

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]

Output: 3

 

Example 2:

Input: [3,4,-1,1]

Output: 2

 

Example 3:

Input: [7,8,9,11,12]

Output: 1

 

-Summary-

1. Set first positive integer as 1 --> posNum

2. loop-through the nums and check if posNum is in the nums list. (max int: 2^31 -1)

  - if there is, adding 1 more value to posNum and find the next positive number.

  - if not found, then return that value immediately.

다른사람이 푼 답을 보니 아래와 같은 방법으로도 풀수 있다.

leetcode.com/problems/first-missing-positive/discuss/17161/Python-O(n)-and-O(nlgn)-solutions.

 

Python O(n) and O(nlgn) solutions. - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

# O(nlgn) time
def firstMissingPositive(self, nums):
    nums.sort()
    res = 1
    for num in nums:
        if num == res:
            res += 1
    return res

모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]

'LeetCode > Problems' 카테고리의 다른 글

Daily Coding Problem #5  (0) 2020.06.19
Floor and Ceiling of a Binary Search Tree  (0) 2020.06.19
LeetCode 665. Non-decreasing Array  (0) 2020.06.18
LeetCode 136. Single Number  (0) 2020.06.17
LeetCode 238. Product of Array Except Self [Array]  (0) 2020.06.16

댓글