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

题目

给你一个未排序的整数数组 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

    }

总结

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

算法确实重要。

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

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

相关推荐
AllData公司负责人5 分钟前
亲测丝滑,体验跃迁|AllData通过集成开源项目RustFS,多模态数据存储新范式
java·大数据·数据库·算法·数据分析·rustfs
磊 子9 分钟前
AVL树的讲解
数据结构·算法
Trouvaille ~15 分钟前
【Redis篇】Hash 哈希:字段级操作与对象存储的最佳实践
数据库·redis·后端·算法·缓存·哈希算法·键值对
悠仁さん23 分钟前
数据结构 树 二叉树 堆 (链式二叉树模拟实现篇)
数据结构·算法
z2005093034 分钟前
今日算法(带回文问题的回溯)
算法·leetcode·回溯
洛水水36 分钟前
【力扣100题】55.编辑距离
算法·leetcode·动态规划
洛水水1 小时前
【力扣100题】62.滑动窗口最大值
数据结构·算法·leetcode
IronMurphy1 小时前
算法五十一 64. 最小路径和
算法
醒醒该学习了!1 小时前
Prompt提示词——带有深度思考模型的提示方法(理论篇)
人工智能·算法·prompt
君为先-bey1 小时前
Latte——视频生成的潜在扩散变换器
算法·机器学习·音视频·扩散模型