Arrange 0's & 1's in a array

前端 未结 16 2017
独厮守ぢ
独厮守ぢ 2020-12-04 13:36

This is one of an interview question which I had recently. I would like to know others perception of approach for this problem.

Question:

Yo

16条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 14:32

    Okey, here is my approach.

    e.g a[] = { 1,0,0,0,1,1,1,0,0,1};

    Pseudocode:

    1. Have two counters, count1 = 0 and count2 = (n/2)+1
    2. Traverse through the array,

      if(arr[ i ] == 1) 
      { 
          arr[ i ] = count1++;
      } else { 
          arr[ i ] = count2++ 
      };
      
    3. At the end of the traversal, you have array filled with numbers 0 to n-1 like:

      a[ ] = { 0, 5, 6, 7, 1, 2, 3, 8, 9 4}
      
    4. Now the problem comes to sort the above resultant array, this can be done in O(N) as below:

      for(j = 0; j <= 1; j++)  
      {
          for(i = 0; i

      Note: j loop runs only twice irrespective on 'n' and has constant complexity. The order of this whole loop is 2*n = O(n).

    5. After the array is sorted, Again traverse through the array and set elements arr[0] to arr[n/2] to '1' and arr[(n/2)+1] to arr[n] as '0'.

    Space complexity is constant and time complexity is O(step2) + O(step4) + O(step5) = n + 2n +n = 4*n = O(n).

提交回复
热议问题