codility|codility 之 MissingInteger

最近需要面试技术人员,接触了codility,顺便给自己来个自我检验。
题目: Write a function:
int solution(vector &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 &A) { // write your code in C++14 (g++ 6.2.0) vector temp(A.size()); for (unsigned int i=0; i A.size()) continue; temp[val-1] = 1; }unsigned int k=0; for (; k

【codility|codility 之 MissingInteger】转载请注明原作者及原链接

    推荐阅读