Boolean array reordering in O(1) space and O(n) time

前端 未结 5 730
渐次进展
渐次进展 2020-12-29 03:36

The problem is taken from Elements of Programming Interviews:

Given an array A of n objects with Boolean-valued keys, reorder the array so that objects that have the

5条回答
  •  不知归路
    2020-12-29 04:19

    boolean array[n]; // The array
    int lastTrue = n;
    for (int i = n-1; i >= 0; --i) {
      if (array[i]) {
        swap(array[--lastTrue], array[i]);
      }
    }
    

    After every iteration all elements after lastTrue are true. No two true elements are swapped because if there was a true element between i and lastTrue it would have been encountered already and moved behind lastTrue. This runs in O(n) time and O(1) memory.

提交回复
热议问题