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 2518
醉梦人生
醉梦人生 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:16

    I very much doubt if O(n) time and O(1) is feasible with an array. Some suggest linked list, but you will need a custom linked list where you have direct access to the nodes to do this, ie. language-built-in linked lists won't work.

    Here's my idea using a custom doubly linked list which satisfy the constrained complexities, using [1, 7, -5, 9, -12, 15] as an example:

    Loop through the list, if see a negative, cut it off and add it to the end of the negatives at the front. Each operation is O(1) so total time is O(n). Linked list operations are in-place so O(1) space.

    In detail:

    last_negative_node = null;
    
    at -5: 
    
    cut off -5 by setting 7.next = 9, 
    
    then add -5 to front by -5.next = 1, 
    
    then update last_negative_node = 5 // O(1), the linked list is now [-5, 1, 7, 9, -12, 15]
    
    
    at -12: 
    
    cut off -12 by setting 9.next = 15, 
    
    then add -12 to front by -12.next = last_negative_node.next, 
    
    then update last_negative_node.next = -12,
    
    then update last_negative_node = -12 //O(1), the linked list is now [-5, -12, 1, 7, 9, 15]
    
    no more negatives so done.
    

提交回复
热议问题