Given an array of positive and negative integers, re-arrange it so that you have positive integers on one end and negative integers on other

后端 未结 30 2594
醉梦人生
醉梦人生 2020-12-07 07:37

I recently came across a Microsoft Interview Question for Software Engineer.

Given an array of positive and negative integers, re-arrange it so that you

30条回答
  •  无人及你
    2020-12-07 08:39

    I'm not sure I understand the question correctly, as the answer appears to be too simple:

    • Walk through the array and count negative numbers - O(n)
    • Create a new array of size O(n)
    • Walk through original array and place numbers into the new array. Use the known number of negative numbers to offset the positive ones - O(n)

    Here's a quick way to do it in Python. It slightly differs from the above in first creating an array for the negatives, then appending the positives. So it's not as efficient, but still O(n).

    >>> a = [1,7,-5,9,-12,15]
    >>> print [x for x in a if x < 0] + [y for y in a if y >= 0]
    [-5, -12, 1, 7, 9, 15]
    

    Edit: Ok, now with O(1) space compexity it gets much harder. I'm interested in how to achieve it in O(n) time complexity, too. If it helps, here's a way to keep the O(1) space complexity, but requires O(n^2) time complexity:

    • Start from the leftmost negative number. Walk through the array until you find the next negative number.
    • In a new loop, exchange the negative number with the positive number left of it. Do this until you reach the other negative numbers. This ensures the order of the numbers remains unchanged.
    • Rince and repeat until you reach the end of the array when looking for a new negative number.

提交回复
热议问题