花了一小时写了道困难题,check it out.
0ms,击败100%的java用户,51mb击败98%的java用户
遍历数组,某个元素 nums[i] 满足 1 <= nums[i] <= len,则将 temp[nums[i] - 1] 设为 true。使用哈希数组记录大小为数组长度内的数,找到数组是否存在1-n的字串,存在返回n+1,不存在返回1,特殊情况:nums[]为从1开始的递增序列,哈希数组均为true不返回,则返回默认值len+1
public int firstMissingPositive(int[] nums) {
int len = nums.length;
boolean[] temp = new boolean[len];
for (int i = 0; i < len; i++) {
if (1 <= nums[i] && nums[i] <= len) {
temp[nums[i] - 1] = true;
}
}
for (int i = 0; i < temp.length; i++) {
if (temp[i] != true) {
return i+1;
}
}
return len+1;
}