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

题目

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

    }

总结

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

算法确实重要。

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

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

相关推荐
PassLink_1 小时前
AlgorithmVisualizer项目改进与部署-网页算法可视化
算法·编程·开源项目·本地部署·算法可视化·源码改进
GalaxyPokemon2 小时前
LeetCode - 2. 两数相加
java·前端·javascript·算法·leetcode·职场和发展
编程绿豆侠2 小时前
力扣HOT100之堆:347. 前 K 个高频元素
算法·leetcode·哈希算法
GalaxyPokemon4 小时前
归并排序:分治思想的高效排序
数据结构·算法·排序算法
ThreeYear_s4 小时前
基于FPGA的PID算法学习———实现PI比例控制算法
学习·算法·fpga开发
Coding小公仔7 小时前
LeetCode 240 搜索二维矩阵 II
算法·leetcode·矩阵
C++chaofan7 小时前
74. 搜索二维矩阵
java·算法·leetcode·矩阵
Studying 开龙wu8 小时前
机器学习监督学习实战五:六种算法对声呐回波信号进行分类
学习·算法·机器学习
Mi Manchi268 小时前
力扣热题100之二叉树的层序遍历
python·算法·leetcode
wu~9708 小时前
leetcode:42. 接雨水(秒变简单题)
算法·leetcode·职场和发展