Arrange 0's & 1's in a array

前端 未结 16 2011
独厮守ぢ
独厮守ぢ 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:33

    Here is solution that works for an array of int. You can modify it.

    sort (int [] a) {
       int pos = 0;
       for (int i = 1; i < a.length; i++) {
           if (a[i] == 0 && a[pos] == 1) {
               swap(a, pos, i);   // this makes all 0's go to the left.
               pos++;
           }
       } 
    }
    

提交回复
热议问题