题:https://leetcode.com/problems/first-missing-positive/
题目大意
对于一个数组,找出数组中缺失的最小正整数,且 算法的时间复杂度为O(n),空间复杂度为O(1)。
思路
空间复杂度 O(n)
对于这种问题,最简单的方法就是使用 set 记录 数组中已经出现的正整数,然后从1向上遍历找出最小没有出现的正整数。
该方法的时间复杂度O(n),但空间复杂度为O(n)
class Solution {
public int firstMissingPositive(int[] nums) {
Set<Integer> set = new HashSet();
int MAX = 0;
for(int a : nums)
if(a>0){
set.add(a);
MAX = Math.max(MAX,a);
}
int i = 1;
while(i <= MAX){
if(!set.contains(i))
return i;
i++;
}
return MAX+1;
}
}
使用数组下标作为hash ,空间复杂度为 O(1)
HashSet 是 对 数组元素做了hash映射,从而达到了 快速查找的功能。
这里可以使用下标本身作为 hash映射,将 元素映射到 数组的相应下标位置,作为Hash。这样我们只用 根据下标就可以判断出 数组的元素 是否 出现在 数组中。
class Solution {
public void swap(int[] nums,int a,int b){
nums[a] = nums[a] ^ nums[b];
nums[b] = nums[a] ^ nums[b];
nums[a] = nums[a] ^ nums[b];
}
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for(int i = 0 ; i < n ; i++){
while(nums[i]> 0 && nums[i]<n && nums[nums[i]-1] != nums[i]){
swap(nums,i,nums[i]-1);
}
}
for(int i = 0 ;i < n ; i++)
if(nums[i]!=i+1)
return i+1;
return n+1;
}
}