41. 缺失的第一个正数 First Missing Positive
Given an unsorted integer array nums
, find the smallest missing positive integer.
Follow up: Could you implement an algorithm that runs in O(n)
time and uses constant extra space.?
Input: nums = [1,2,0]
Output: 3
方法:
将小于0和大于n的值置为n+1
将绝对值在1到n之间的数,标记i-1位置为负
第一个正数+1则是确实值
public int firstMissingPositive(int[] nums) { int n = nums.length; for (int i = 0 ; i < n; i++){ if (nums[i] <= 0 || nums[i ]> n) nums[i] = n + 1; } for(int i = 0; i < n; i++){ int num = Math.abs(nums[i]); if(num <= n){ nums[num - 1] = -Math.abs(nums[num - 1]); } } for (int i = 0; i < n; i++){ if (nums[i] > 0) return i + 1; } return n + 1;· }
参考链接:
https://leetcode.com/problems/first-missing-positive/
https://leetcode-cn.com/problems/first-missing-positive