LeetCode – 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.
虽然不能再另外开辟非常数级的额外空间,但是可以在输入数组上就地进行swap操作。
思路:交换数组元素,使得数组中第i位存放数值(i+1)。最后遍历数组,寻找第一个不符合此要求的元素,返回其下标。整个过程需要遍历两次数组,复杂度为O(n)。
下图以题目中给出的第二个例子为例,讲解操作过程。
class Solution { public int firstMissingPositive(int[] nums) { if(nums == null || nums.length == 0){ return 1; } for (int i=0; i<nums.length; i++){ if(nums[i] <= nums.length && nums[i] > 0 && nums[i] != nums[nums[i]-1]){ int temp = nums[nums[i]-1]; nums[nums[i]-1] = nums[i]; nums[i] = temp; i--; } } for(int i=0; i<nums.length; i++){ if(nums[i] != i+1){ return i+1; } } return nums.length+1; } }
posted on 2018-07-27 10:04 IncredibleThings 阅读(109) 评论(0) 编辑 收藏 举报