功能解决方案($ A);
在给定一个由N个整数组成的数组A的情况下,返回不存在于A中的最小正整数(大于0)。
例如,给定A = [1、3、6、4、1、2],该函数应返回5。
给定A = [1、2、3],该函数应返回4。
给定A = [-1,-3],该函数应返回1。
为以下假设写出有效的算法:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000].
以下是我的尝试:
function solution($A) {
// write your code in PHP7.0
$n=1;
while($n > 0 && $n <= 1000000)
$n ++;
echo $A=$n+1;
}
echo solution;
?>```
答案 0 :(得分:2)
尝试一下,不需要循环:
<?php
function solution($set) {
$diff = array_diff(range(1, max($set)), $set);
sort($diff);
return !isset($diff[0]) ? max($set) + 1 : ($diff[0] < 1 ? 1 : $diff[0]);
}
echo solution([39, 68, 47, 2, 19, 64]); // 1
echo solution([1, 3, 6, 4, 1, 2]); // 5
echo solution([1, 2, 3]); // 4
echo solution([-1, -3]); // 1
答案 1 :(得分:0)
这里是一种单线,可以打动您的教授或因不遵循指示而被踢出课堂:
php > function solution(array $A) { return max(array(1,min(array_diff(range(1,100000),$A)))); }
php > echo solution([39, 68, 47, 2, 19, 64]);
1
php > echo solution([1,3,6,4,1,2]);
5
php > echo solution([-1,-3]);
1
php > echo solution([1,2,3]);
4
它将生成数组N(1-1,000,000),并对您的输入A运行array_diff,并返回该比较的最低结果;如果小于或等于0,则返回1。
答案 2 :(得分:0)
function solution($A) {
$smallest = 1;
while(in_array($smallest, $A)){
$smallest++;
}
return $smallest;
}
以上是最小的代码,但具有 O(N ^ 2)复杂度,成功率为66%
function solution($A) {
$flipped = array_flip($A);
$smallest = 1;
while (isset($flipped[$smallest])){
$smallest++;
}
return $smallest;
}
检测到的时间复杂度: O(N)或O(N * log(N)),成功率为100%