41.First-Missing-Positive

41. First Missing Positive

题目地址

https://leetcode.com/problems/first-missing-positive/

题目描述

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

Note:
Your algorithm should run in O(n) time and uses constant extra space.

代码

Approach #1

The key here is to use swapping to keep constant space and also make use of the length of the array, which means there can be at most n positive integers. So each time we encounter an valid integer, find its correct position and swap. Otherwise we continue.

Approach #2 Index as a hash key

Complexity Analysis

  • Time complexity : O(N) since all we do here is four walks along the array of length N.

  • Space complexity : O(1) since this is a constant space solution.

Last updated

Was this helpful?