美文网首页C++
codility 之 MissingInteger

codility 之 MissingInteger

作者: BeastHan | 来源:发表于2018-03-04 00:16 被阅读11次

最近需要面试技术人员,接触了codility,顺便给自己来个自我检验。

题目:

Write a function:
int solution(vector<int> &A);
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.
Given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.

Assume that:

  • 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].

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

解题要点:

  1. 经过分析,结果范围一定是在[1, N+1]区间之内;//分析出这一点对于解题很重要,我最开始没想到这一点,进行了一些多余操作
  2. 一定注意对时间复杂度的控制,本题目难度较低,算法的优化主要是在时间复杂度方面;

参考答案:

由于时间比较紧,写的不规范的地方请看官们多担待

int solution(vector<int> &A) {
    // write your code in C++14 (g++ 6.2.0)
    vector<int> temp(A.size());
    for (unsigned int i=0; i<A.size(); i++)
    {
        int val = A[i];
        if (val <= 0 || val > A.size()) continue;
        temp[val-1] = 1;
    }
    
    unsigned int k=0;
    for (;k<temp.size();k++)
    {
        if (temp[k]==0) break;
    }
    
    return k+1;
}

转载请注明原作者及原链接

相关文章

网友评论

    本文标题:codility 之 MissingInteger

    本文链接:https://www.haomeiwen.com/subject/ouaxfftx.html