欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Leetcode 缺失的第一个正整数

Leetcode 缺失的第一个正整数

2025/9/19 6:03:03 来源:https://blog.csdn.net/coldasice342/article/details/142250767  浏览:    关键词: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.
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] - 1while(nums[i] > 0 && nums[i] <=n && nums[i] != nums[nums[i] - 1]) {swap(nums[i], nums[nums[i] - 1]);}}//然后,我们遍历数组,当下标 i 对应的值不等于 i + 1 时,返回 i + 1for(int i = 0; i < n; i++) {if(nums[i] != i + 1) {return i + 1;}}//如果在上面的循环中并没有return,说明数组所以元素值被排列成了 1,2,...,nreturn n + 1;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词