隔离偶数和奇数,保持顺序,O(1)空间,O(N)时间复杂度

时间:2017-04-30 19:50:46

标签: algorithm sorting

Input  = {12, 34, 45, 9, 8, 90, 3} 
Output = {12, 34, 8, 90, 45, 9, 3}

给定一个整数数组,在所有奇数之前重新排列所有偶数整数,但是使用O(1)空间和O(n)时间复杂度将它们的原始序列保持在数组中。

思想:

Algorithm: segregateEvenOdd()
1) Initialize two index variables left and right:  
            left = 0,  right = size -1 
2) Keep incrementing left index until we see an odd number.
3) Keep decrementing right index until we see an even number.
4) If lef < right then swap arr[left] and arr[right]

但这不能保证订单是一样的。

如果我想使用O(1)空间来解决这个问题该怎么办?

1 个答案:

答案 0 :(得分:-1)

你必须存储最后的奇数和最后的偶数位置,

1. Initialize both last_odd, last_even to -1;
2. Iterate over array
   - Check if array[i] is odd or even,
   - if diff(last_odd/last_even,i) >= 2 and last_odd/even not equal to 
     -1:
        if (element is odd/even) new index = last_odd/even+1
        - store element value in temp
        - move elements from new_index up to i one to right 
          starting back from i-1 down to new_index.
        - store temp in new_index
        - store last_odd/even as new_index accordingly and add to 
          last_even/odd the diff(which is +1)
   - else store last_odd/even as i accordingly