算法---缺失的第一个正数

题目

给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。

复制代码
请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。


示例 1:

输入:nums = [1,2,0]
输出:3
示例 2:

输入:nums = [3,4,-1,1]
输出:2
示例 3:

输入:nums = [7,8,9,11,12]
输出:1


提示:

1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1

解决思路

借用map 就可以实现,但是如果不借用map,在原空间上,也可以实现,不过想要使用原来的数据,会有侵略性,会把原来的数据修改掉。

解决方法

方法一:

kotlin 复制代码
    fun firstMissingPositive(nums: IntArray): Int {
        val size = nums.size
        nums.forEachIndexed { index, i ->
            if (i <= 0) {
               nums[index] = size + 1
            }
        }
        nums.forEachIndexed { index, i ->
            if (i.absoluteValue in 1..size && nums[i.absoluteValue -1]  > 0) {
                nums[i.absoluteValue -1] = -nums[i.absoluteValue -1]
            }
        }

        nums.forEachIndexed { index, i ->
            if (i >= 0){
                return index + 1
            }
        }

        return size + 1
    }

方法二:

kotlin 复制代码
    fun firstMissingPositive2(nums: IntArray): Int {
        val size = nums.size
        var temp = 0

        nums.forEachIndexed { index, _ ->

            while (nums[index] in 1 until size && nums[nums[index] - 1] != nums[index]) {

                temp = nums[nums[index] - 1]
                nums[nums[index] - 1] = nums[index]
                nums[index] = temp
            }
        }
        nums.forEachIndexed { index, i ->
            if (index != i - 1) {
                return index + 1
            }
        }

        return size + 1

    }

总结

算法是很看一个人的思维逻辑的,所以很多都会考验一下算法。

算法确实重要。

做了快一年算法了,确实 学习如园中小草,不见其增,日有所长

面试遇到算法就很轻松就过了

相关推荐
南玖yy30 分钟前
数据结构C语言练习(栈)
c语言·数据结构·算法
阿镇吃橙子43 分钟前
一些手写及业务场景处理问题汇总
前端·算法·面试
酱酱哥玩AI1 小时前
Trae编译器:实现多目标班翠鸟优化算法(IPKO)无人机路径规划仿真(Python版),完整代码
算法
MPCTHU1 小时前
二叉树、排序算法与结构图
数据结构·算法·排序算法
亓才孓1 小时前
[leetcode]树的操作
算法·leetcode·职场和发展
王禄DUT1 小时前
化学方程式配平 第33次CCF-CSP计算机软件能力认证
开发语言·c++·算法
wuqingshun3141591 小时前
蓝桥杯 XYZ
数据结构·c++·算法·职场和发展·蓝桥杯
DreamByte2 小时前
C++菜鸟教程 - 从入门到精通 第五节
开发语言·c++·算法
南玖yy2 小时前
数据结构C语言练习(两个队列实现栈)
c语言·数据结构·算法
明朝百晓生2 小时前
【强化学习】【1】【PyTorch】【强化学习简介优化框架】
算法