[leetcode]41. First Missing Positive(Java)

来源:互联网 发布:mips linux gnu gcc 编辑:程序博客网 时间:2024/06/07 07:25

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


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

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

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

Java code:


package go.jacob.day622;import java.util.HashSet;public class Demo1 {/* * 运行时间:12ms  * 该解法:O(n)time,O(1)space  * leetcode网友@siyang3的解答 */public int firstMissingPositive(int[] nums) {if (nums == null || nums.length < 1)return 1;int i = 0;while (i < nums.length) {if (nums[i] == i + 1 || nums[i] <= 0 || nums[i] > nums.length)i++;// 防止死循环.条件不能是else if (nums[i] != i + 1)//比如[1,1]会引起死循环else if (nums[nums[i] - 1] != nums[i])swap(nums, i, nums[i] - 1);elsei++;}i = 0;while (i < nums.length && nums[i] == i + 1)i++;return i + 1;}private void swap(int[] nums, int i, int j) {int temp = nums[i];nums[i] = nums[j];nums[j] = temp;}/* * 运行时间:14ms  * O(n)time,O(n)space */public int firstMissingPositive_1(int[] nums) {if (nums == null || nums.length < 1)return 1;int length = nums.length;HashSet<Integer> set = new HashSet<Integer>();int min = Integer.MAX_VALUE;int max = Integer.MIN_VALUE;for (int i = 0; i < length; i++) {if (nums[i] > 0) {set.add(nums[i]);if (nums[i] > max)max = nums[i];if (nums[i] < min)min = nums[i];}}if (max == Integer.MIN_VALUE || min > 1)return 1;int result = -1;boolean flag = false;for (int i = 1; i <= max; i++) {if (!set.contains(i)) {result = i;flag = true;break;}}return flag ? result : max + 1;}}


原创粉丝点击