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 2522
醉梦人生
醉梦人生 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:19

    You can use 2 queues and merge them. That way, you only iterate once on the first array and once each sub queue.

    negatives = []
    positives = []
    
    for elem in array:
      if elem >= 0:
        positives.push(elem)
      else
        negatives.push(elem)
    
    result = array(negatives, positives)
    

提交回复
热议问题