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

前端 未结 5 699
渐次进展
渐次进展 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:08

    Let the array have 0 based index and let it have n elements. Then you can do the following ( pseudo code below )

         // A[] is your array
         i = 0
         k = 0
         for i from 0 to n-1
              if A[i] is true
                 swap A[i] and A[k]
                 increment k
    

    Time complexity is O(n) and extra space is only used for two variables i and j so memory is O(1). This way ordering is preserved amongst false and true values. ( This method puts true ones first you can change it according to your requirement ).

提交回复
热议问题