栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

数组-[41] 缺失的第一个正数

Java 更新时间:发布时间: 百科书网 趣学号

// @lc code=start
class Solution {
    public int firstMissingPositive(int[] nums) {
        int size = nums.length;
        for(int i = 0; i < size; i++){
            int ind = nums[i] - 1;

            // 当对应元素nums[ind] - 1 == ind 时无需处理,eg.[1,2,3]
            if(i == ind)
                continue;

            // ind < 0 || ind >= size : 当元素值超出[0,nums.length)时即认为ind对应位置元素不存在
            // nums[ind] == nums[i]   : 当对应位置 ind已经存在元素则当前i位置设为不存在
            if(ind < 0 || ind >= size || nums[ind] == nums[i]){
                nums[i] = Integer.MIN_VALUE;
                continue;
            }

            // 交换元素
            int temp = nums[ind];
            nums[ind] = nums[i];
            nums[i] = temp; 

            // 再次遍历当前i索引
            i--;
        }
        
        // 返回第一个元素值为Integer.MIN_VALUE的位置 + 1
        for(int i = 0; i < size; i++)
            if(nums[i] == Integer.MIN_VALUE)
                return i + 1;

        // 如果全部不为Integer.MIN_VALUE 则 直接返回 size + 1
        // eg.[1,2,3,4,5] return 6
        return size + 1;
    }
}
// @lc code=end

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/273871.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号