first-missing-positive

来源:互联网 发布:视频模糊修复软件 编辑:程序博客网 时间:2024/06/04 19:05
packagecom.ytx.array;
importjava.util.Arrays;
/** 题目:first-missing-positive
 *     
 *     描述: Given an unsorted integer array, find the first missing positive integer.
                    For example,
                    Given[1,2,0]return3,
                    and[3,4,-1,1]return2.
                    Your algorithm should run in O(n) time and uses constant space.
 *
 *@authoryuantian xin
 *
 */
publicclass First_missing_positive {
       
       
       publicint firstMissingPositive(int[]A) {
             if(A== null || A.length< 1) return 1; 
       
       //把小于等于A.length的正数A[i]放到第A[i]-1个位置上 
       for (inti = 0; i < A.length;i++) { 
           while (A[i] > 0 &&A[i] <=A.length&& A[A[i] - 1] !=A[i]) { 
               int tmp = A[A[i] - 1]; 
               A[A[i] - 1] = A[i]; 
               A[i] =tmp
            } 
        } 
         
       for (inti = 0; i < A.length;i++) { 
           if (A[i] !=i + 1) { 
               return i + 1; 
            } 
        } 
         
       return A.length+ 1; 
    }
       publicstatic void main(String[]args) {
             /*int A [] = {3,4,-1,1};*/
             intA [] = {1000,-1};
             intres;
             res= new First_missing_positive().firstMissingPositive(A);
             System.out.println(res);
       }
}
原创粉丝点击