Leetcode 41 First Missing Positive
阿新 • • 發佈:2018-12-23
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.
這個題是查詢第一個最小的正整數。
public class Solution { public int firstMissingPositive(int[] nums) { if (nums == null || nums.length == 0) // 防止越界 return 1; for (int i = 0; i < nums.length; i++) { // nums[i] - 1 < nums.length 超出範圍不交換 nums[i] != nums[nums[i] - 1] 相等不交換 while (nums[i] > 0 && nums[i] != i + 1 && nums[i] - 1 < nums.length && nums[i] != nums[nums[i] - 1]) { swap(nums, i, nums[i] - 1); } } for (int i = 0; i < nums.length; i++) { if (nums[i] != i + 1) { return i + 1; // 第一個不相等就返回 } } return nums[nums.length - 1] + 1; // 陣列交換後是有序正數,就返回最大 + 1 } public void swap(int[] nums, int i, int j) { nums[i] = nums[i] ^ nums[j]; nums[j] = nums[i] ^ nums[j]; nums[i] = nums[i] ^ nums[j]; } }