algorithm - 返回最小正整数 > 0
问题描述
参考以下问题:
That, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
1 Given A = [1, 2, 3], the function should return 4.
2 Given A = [−1, −3], the function should return 1.
在给定1
= 为什么它期望返回 4。他们是如何得出 4 的?
并给出2
= 为什么它期望返回 1。他们是如何得出 1 的?
当问题说明 o 得到大于 0 的正整数时,(integer> 0)
其中that does not occur in A.
是不明确的(我假设它需要一个唯一的值在里面A
?。
我错过了什么?
PS:我没看懂标题MISSING INTEGER
解决方案
一种解决方案是选择输入数组的最小正值,然后检查下一个正整数是否也存在于输入数组中。如果不是,则返回它,如果存在,则检查下一个整数是否存在,依此类推。
此外,时间复杂度在最坏的情况O(n log(n))
下n
是输入数组的大小,因为您永远不必将初始猜测增加超过n
(一行中不能有多个n
整数),并且排序是 O(n log(n))
.
一些伪代码可能如下所示:
int findSmallestInt(int[] array) {
// sort input array
// check if no positive elements
if (array[array.size - 1] < 0) {
return 1;
}
int smallestInt = array[0];
// make sure smallestInt is positive
for (int i = 0; i < array.size && smallestInt < 0; i++) {
smallestInt = array[i];
}
for (int i = 0; i < array.size; i++) {
smallestInt += 1;
if (!array.contains(smallestInt)) {
return smallestInt;
}
}
}
另外,回答你上面的两个问题:
在 1 中它返回 4,因为它是 A 中不存在的最小正整数,在 2 中它返回 1,因为它是 A 中不存在的最小非零正整数。
推荐阅读
- ios - XML解析中的URL没有响应-Alamofire Swift 5
- azure - Azure DevOps - 小部件大小
- javascript - javascript regex replace 1st and 3rd space in a string
- postgresql - 如何在flyway创建的postgresql jdbc连接上设置时区?
- jenkins-pipeline - 如何从另一个声明性脚本执行詹金斯声明性脚本?
- angular - RxJs Observable 如何处理成功
- c - 用 CMake 编译 CU 和 C 文件
- azure-devops - 在多个作业中下载相同的管道工件 latestFromBranch
- c# - 使用 Count() 函数会引发“内部 .NET Framework 数据提供程序错误 1025”。
- c# - XML 验证然后使用 C# 进行转换