题解 | #缺失的第一个正整数#
缺失的第一个正整数
http://www.nowcoder.com/practice/50ec6a5b0e4e45348544348278cdcee5
自定义哈希函数
因为要寻找的是最小的正整数,我们可以将数组中的负数先移出我们的排查范围;
如果遍历到的nums[i]小于nums.length,将该数字对应的下标改为负数,表示该位置的正整数已出现
参考leetcode题解:https://leetcode-cn.com/problems/first-missing-positive/solution/tong-pai-xu-python-dai-ma-by-liweiwei1419/
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int minNumberDisappeared (int[] nums) {
// write code here
int n = nums.length;
//先将数组中小于0的替换为大于n的数,确保数组中没有负数
for (int i = 0; i < n; ++i) {
if (nums[i] <= 0) {
nums[i] = n + 1;
}
}
for (int i = 0; i < n; ++i) {
int num = Math.abs(nums[i]);
//如果当前位置绝对值小于n,则是符合目标的元素,将该值对应的下标改为负数
if (num <= n) {
nums[num - 1] = -Math.abs(nums[num - 1]);
}
}
for (int i = 0; i < n; ++i) {
if (nums[i] > 0) {
return i + 1;
}
}
return n + 1;
}
}
海康威视公司福利 1382人发布

查看6道真题和解析