codility 之 MissingInteger

最近需要面试技术人员,接触了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;
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,453评论 0 10
  • “烤红薯~卖烤红薯~” 窗外传来一声声烤红薯的叫卖声,把我带回香甜的记忆中。 冬天,窗外下着雪,我们一家人围坐在火...
    王孟姐姐阅读 279评论 0 2
  • 2017.8.25就是上周五我下载了简书这个app。不知从何起我喜欢上了写文字,每当我有想法就记录在微博上,慢慢的...
    页生活阅读 147评论 0 0
  • ----一只种花家的兔子随想 前言:好久没有更文,不是小二哥懒...
    古城店小二阅读 635评论 0 0
  • 突然从梦中惊醒,梦里全是一个人;努力去记住梦里的每个画面,湿的不是枕塌,不是衣襟,原来是整个身体。仿佛在梦里感受到...
    白乐随心阅读 251评论 0 0