2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_41.java 1.03 KB
一键复制 编辑 原始数据 按行查看 历史
Charies Gavin 提交于 2020-02-06 12:44 . 初始化 myleetcode 项目
package com.hit.basmath.interview.top_interview_questions.hard_collection.array_and_strings;
/**
* 41. First Missing Positive
* <p>
* Given an unsorted integer array, find the smallest missing positive integer.
* <p>
* Example 1:
* <p>
* Input: [1,2,0]
* Output: 3
* <p>
* Example 2:
* <p>
* Input: [3,4,-1,1]
* Output: 2
* <p>
* Example 3:
* <p>
* Input: [7,8,9,11,12]
* Output: 1
* <p>
* Note:
* <p>
* Your algorithm should run in O(n) time and uses constant extra space.
*/
public class _41 {
public int firstMissingPositive(int[] nums) {
int i = 0;
while (i < nums.length) {
if (nums[i] == i + 1 || nums[i] <= 0 || nums[i] > nums.length) i++;
else if (nums[nums[i] - 1] != nums[i]) swap(nums, i, nums[i] - 1);
else i++;
}
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;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助