Wednesday, May 15, 2013

Move zeros to end C++

Given an unsorted integer array, place all zeros to the end of the array without changing the sequence of non-zero elements. (i.e. [1,3,0,8,12, 0, 4, 0,7] --> [1,3,8,12,4,7,0,0,0])

思路:用个index记录当前需要填充的位置,扫一遍就行了,跟quicksort思路一致。复杂度O(n)
  1. void pushzeros(int A[], int n){  
  2.   
  3.   int index = 0;  
  4.   
  5.   for(int i = 0; i < n; i++){  
  6.   
  7.     if(A[i] != 0){  
  8.          int tmp = A[index];  
  9.   
  10.          A[index++] = A[i];  
  11.   
  12.          A[i] = tmp;  
  13.   
  14.     }  
  15.      
  16.   }     
  17.   
  18. }   

No comments:

Post a Comment