Arrange 0's & 1's in a array

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

    using std::stable_partition together with std::equal_to and std::binder1st should do the trick in a nice, functional, STL-like way:

    using namespace std
    stable_partition(&array[0], &array[N], binder1st(equal_to(), 1));
    

    Of course, this assumes that the elements of array have some comparison operator defined (i.e. you can say array[i]==1...). If they are just integers, it wouldn't make any sense to maintain the order ...

    As to complexity: In order to be O(N), stable_partition needs extra memory. If the algorithm fails to allocate that extra memory, it performs in O(N log N).

提交回复
热议问题