代码拉取完成,页面将自动刷新
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;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。