查找试题--互换函数swap初试

来源:互联网 发布:永诚网络 编辑:程序博客网 时间:2024/05/01 21:14

题目:

Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2

 

试题解答:

#include "stdafx.h"
#include "map"
#include "string"
using namespace std;
int firstMissingPositive(int nums[], int n);

int main(int argc, char* argv[])
{
    int tem[10] = {101, 102, 103, 104,105,106,107,108,109,100};
 
    int ret=firstMissingPositive(tem, 10);
 printf(" ret = %d \n", ret);

 return 0;
}

int firstMissingPositive(int A[], int n)
{
 for(int i = 0; i < n; ++ i)
  if(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i])
   swap(A[i], A[A[i] - 1]);
  
        for(i = 0; i < n; ++ i)
            if(A[i] != i + 1)
                return i + 1;

        return n + 1;
}


 

0 0
原创粉丝点击