繁体   English   中英

使用 Function-int solution(vector<int> &一个);

[英]Return the smallest positive integer that does not occur in an array A of N integers using Function- int solution(vector<int> &A);

写一个函数:

int solution(vector<int> &A);

即,给定一个包含N个整数的数组A ,返回A中未出现的最小正整数(大于 0)。

例如,给定 A = [1, 3, 6, 4, 1, 2],函数应该返回 5。

给定 A = [1, 2, 3],函数应该返回 4。

给定 A = [-1, -3],函数应该返回 1。

为以下假设编写一个有效的算法:

N是 [1..100,000] 范围内的整数; 数组A的每个元素都是 [-1,000,000..1,000,000] 范围内的整数。

我下面的解决方案有 100% 的正确性,但性能只有 25%。 我可以做些什么来提高我的绩效评级?

int solution(vector<int> &A) {
    int s=A.size();
    int x = 1;
    bool neg=true;
    for (int i=0; i<s;i++){     //check if all integers are negative
        if (A[i]>0){            
            neg = false;        
            goto check;
        }
    }
    check:
    if (neg==true){
        return x;     //returns 1 if all integers are negative
    }
    for (int i=0; i<s; i++){
        for(int j=0; j<s; j++){         
            if (A[j] == x ){
                x=A[j]+1;
                break;
            }
        }
    }
    return x;
}

这是我的代码分数。

如评论中所述,您的方法需要O(n^2)时间。

要获得更快的结果,您需要更好的算法。

提到的一件事是对向量进行排序。 同时扔掉所有<= 0的东西,然后你可以通过结果向量并检查第一个洞。 这让你减少到O(n log n)时间。

提到的另一种算法是使用无序集或vector<bool>并标记所有存在的数字,然后找到第一个不存在的数字。 请注意,对于 n 个数字的输入,答案必须是介于 1 和 n + 1 之间的数字。 所以你可以大大减少你需要的无序集或向量的大小。 最多12.5kb的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM