首页 > 学院 > 开发设计 > 正文

leetcode - 41.First Missing Positive

2019-11-06 07:31:12
字体:
来源:转载
供稿:网友

First Missing Positive

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.

Solution:

public int firstMissingPositive(int[] nums) { for (int i = 0; i < nums.length; i++) { while (nums[i] > 0 && nums[i] < nums.length && nums[i] != nums[nums[i] - 1]) { int temp = nums[i]; nums[i] = nums[temp - 1]; nums[temp - 1] = temp; } } for (int i = 0; i < nums.length; i++) { if (nums[i] != i + 1) { return i + 1; } } return nums.length + 1; }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表