41 First Missing Positive

本文介绍了一种在不使用额外空间的情况下寻找数组中缺失的最小正整数的方法。通过原地交换数组元素,使每个位置上的数值等于该位置的索引加一,最后遍历数组找到第一个不符合此规律的位置,即为所求。此算法复杂度为O(n),适用于面试和技术挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文字分析部分摘自:

http://blog.youkuaiyun.com/nanjunxiao/article/details/12973173


思路:

虽然不能再另外开辟非常数级的额外空间,但是可以在输入数组上就地进行swap操作。

思路:交换数组元素,使得数组中第i位存放数值(i+1)。最后遍历数组,寻找第一个不符合此要求的元素,返回其下标。整个过程需要遍历两次数组,复杂度为O(n)

下图以题目中给出的第二个例子为例,讲解操作过程。



public static int firstMissingPositive(int[] nums)
	{
		int len=nums.length;
		if(len==0)
			return 1;
		
		for(int i=0;i<len;i++)
		{
			while(nums[i]!=i+1)
			{
				if(nums[i]>=len||nums[i]<=0||nums[i]==nums[nums[i]-1])
					break;
				int temp=nums[i];
				nums[i]=nums[temp-1];
				nums[temp-1]=temp;
			}
		}
		
		for(int i=0;i<len;i++)
			if(nums[i]!=i+1)
				return i+1;
		
		return len+1;
	}



c++中文C. Breach of Faith time limit per test2 seconds memory limit per test256 megabytes Breach of Faith - Supire feat.eili You and your team have worked tirelessly until you have a sequence a1,a2,…,a2n+1 of positive integers satisfying these properties. 1≤ai≤1018 for all 1≤i≤2n+1 . a1,a2,…,a2n+1 are pairwise distinct. a1=a2−a3+a4−a5+…+a2n−a2n+1 . However, the people you worked with sabotaged you because they wanted to publish this sequence first. They deleted one number from this sequence and shuffled the rest, leaving you with a sequence b1,b2,…,b2n . You have forgotten the sequence a and want to find a way to recover it. If there are many possible sequences, you can output any of them. It can be proven under the constraints of the problem that at least one sequence a exists. Input Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤104 ). The description of the test cases follows. The first line of each test case contains one integer n (1≤n≤2⋅105 ). The second line of each test case contains 2n distinct integers b1,b2,…,b2n (1≤bi≤109 ), denoting the sequence b . It is guaranteed that the sum of n over all test cases does not exceed 2⋅105 . Output For each test case, output 2n+1 distinct integers, denoting the sequence a (1≤ai≤1018 ). If there are multiple possible sequences, you can output any of them. The sequence a should satisfy the given conditions, and it should be possible to obtain b after deleting one element from a and shuffling the remaining elements. Example InputCopy 4 1 9 2 2 8 6 1 4 3 99 2 86 33 14 77 2 1 6 3 2 OutputCopy 7 9 2 1 8 4 6 9 86 99 2 77 69 14 33 4 6 1 2 3 1
03-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值