数组Mex

来源:互联网 发布:数码视讯软件开发 编辑:程序博客网 时间:2024/06/08 13:52

题目描述:

       请设计一个高效算法,查找数组中未出现的最小正整数。
给定一个整数数组A和数组的大小n,请返回数组中未出现的最小正整数。保证数组大小小于等于500。
测试样例:
[-1,2,3,4],4
返回:1

AC代码:

class ArrayMex {public:     /*void swap(int &t1, int &t2){            int tmp = t1;            t1 = t2;            t2 = tmp;        }  */      int findArrayMex(vector<int> A, int n) {        // write code here        int left=0,right=n,k;        while(left<right){            if(A[left]==left+1)                left++;            else if(A[left]<=left || A[left]>right || A[A[left]-1]==A[left])                A[left]=A[--right];            else{                int tmp = A[left];                A[left] = A[A[left]-1];                A[tmp-1] = tmp;////此处很容易出错,因为A[left]已经改变,不能再使用A[A[left]-1]表达式。            }                //swap(A[left],A[A[left]-1]);//建议使用swap函数。        }        return left+1;    }};


0 0
原创粉丝点击