Leetcode 缺失的第一个正整数

题目意思是找出第一个没出现的最小正整数。

Explanation:

  1. Move Numbers to Correct Positions:

    • The idea is to place each number in its corresponding index. For example, 1 should be at index 0, 2 should be at index 1, and so on. This is done using a while loop to swap the elements until all valid numbers (those within the range 1 to n) are in their respective positions.
  2. Find the First Missing Positive:

    • After the first step, iterate through the array. The first position where the element is not equal to i + 1 is the smallest missing positive integer.
  3. Return n + 1 if all numbers are in correct places:

    • If all numbers are in their correct places, the smallest missing positive integer must be n + 1.

Time Complexity:

  • The time complexity is O ( n ) O(n) O(n) because each element is swapped at most once.

Space Complexity:

  • The space complexity is O ( 1 ) O(1) O(1) since we are using constant extra space.
cpp 复制代码
class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n = nums.size(); //由于数组下标是从0开始,所以值为 n 的元素的下标按顺序是 n - 1
        //例如1的下标是0,2的下标是1...
        for(int i = 0; i < n; i++) {
            //仅当当前元素值的范围介于[1,n]之间,并且它所该移动到的位置上的元素不相等时我们移动它到这个位置
            //值为 nums[i] 的元素按顺序排列的下标是 nums[i] - 1
            while(nums[i] > 0 && nums[i] <=n && nums[i] != nums[nums[i] - 1]) {
                swap(nums[i], nums[nums[i] - 1]);
            }
        }

        //然后,我们遍历数组,当下标 i 对应的值不等于 i + 1 时,返回 i + 1
        for(int i = 0; i < n; i++) {
            if(nums[i] != i + 1) {
                return i + 1;
            }
        }
        //如果在上面的循环中并没有return,说明数组所以元素值被排列成了 1,2,...,n
        return n + 1;
    }
};
相关推荐
TracyCoder1236 分钟前
LeetCode Hot100(6/100)——15. 三数之和
算法·leetcode
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #21:合并两个有序链表(迭代法、原地合并法等多种实现方案详解)
算法·leetcode·链表·优先队列·迭代法·合并两个有序链表·原地合并
源代码•宸1 小时前
Leetcode—47. 全排列 II【中等】
经验分享·后端·算法·leetcode·面试·golang·深度优先
TracyCoder1231 小时前
LeetCode Hot100(7/100)—— 3. 无重复字符的最长子串
算法·leetcode
客卿1232 小时前
力扣二叉树简单题整理--(包含常用语法的讲解)
算法·leetcode·职场和发展
We་ct2 小时前
LeetCode 28. 找出字符串中第一个匹配项的下标:两种实现与深度解析
前端·算法·leetcode·typescript
血小板要健康2 小时前
118. 杨辉三角,力扣
算法·leetcode·职场和发展
漫随流水2 小时前
leetcode回溯算法(491.非递减子序列)
数据结构·算法·leetcode·回溯算法
YuTaoShao3 小时前
【LeetCode 每日一题】1984. 学生分数的最小差值
算法·leetcode·排序算法
wen__xvn3 小时前
基础算法集训第06天:计数排序
数据结构·算法·leetcode