Arrange 0's & 1's in a array

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

    What the heck, here is the whole solution: arr is list of items, item.id is 0 or 1, stored as int.
    This code moves the 0s to the front.

    count = { 0:0, 1:len(arr)/2 }
    for ii in range(len( arr )):
      id = arr[ii].id
      arr[ii].id = count[id]
      count[id] += 1
    for ii in range(len( arr )):
      while arr[ii].id != ii:
        T = arr[ii]
        arr[ii] = arr[arr[ii].id]
        arr[T.id] = T
    for ii in range(len( arr )):
      arr[ii].id = (ii >= len(arr)/2)
    

提交回复
热议问题