First Missing Positive leetcode java


題目

 

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.

Your algorithm should run in O(n) time and uses constant space.

 

題解

題目給了一個unsorted integer array。當然,可以用先排好序的方法走(但是時間復雜度就不能是O(n))。

所以這里提供一個不先排序的算法。

 

注意:題目要求是find the first missing positive integer

也就是說,即便你給的數組是4 5 6 7,看似都一一排好序,但是返回值一定是1,也就是如果給的數組是4 5 7 8 ,答案不是6,是1。

 

因此,有了這個性質,我們就能i和A[i]是否相等來做判斷了。“實現中還需要注意一個細節,就是如果當前的數字所對應的下標已經是對應數字了,那么我們也需要跳過,因為那個位置的數字已經滿足要求了,否則會出現一直來回交換的死循環。”引自 Code Ganker

 

代碼如下:

 1      private  void swap( int[] A,  int i,  int j){
 2          if(A[i]!=A[j]){
 3             A[i]^=A[j];
 4             A[j]^=A[i];
 5             A[i]^=A[j];
 6         }
 7     }
 8      public  int firstMissingPositive( int[] A) {
 9          if(A.length==0||A== null)
10              return 1;
11             
12          for ( int i = 0; i < A.length; i++){
13              if (i != A[i]){
14                  if (A[i] <= 0 || A[i] > A.length-1 || A[i] == A[A[i]])
15                      continue;
16                  else{
17                     swap(A, i, A[i]);
18                     i--;
19                 }
20             }
21         }
22          int k = 1;  
23          while (k < A.length && A[k] == k) 
24             k++;  
25             
26          if(A[0]==k)
27              return k+1;
28          else
29              return k;
30     }

 

一個更易於理解的代碼來自於codeganker:

 1        public  int firstMissingPositive( int[] A) {  
 2          if(A== null || A.length==0)  
 3              return 1;  
 4             
 5          for( int i=0;i<A.length;i++){  
 6              if(A[i]<=A.length && A[i]>0 && A[A[i]-1]!=A[i]){  
 7                  int temp = A[A[i]-1];  
 8                 A[A[i]-1] = A[i];  
 9                 A[i] = temp;  
10                 i--;  
11             }  
12         }  
13         
14          for( int i=0;i<A.length;i++){  
15              if(A[i]!=i+1)  
16                  return i+1;  
17         } 
18         
19          return A.length+1;  
20     }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM