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 2521
醉梦人生
醉梦人生 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:17

    int [] input = {1, 7, -5, 9, -12, 15};
    int [] output = new int [input.length];
    int negativeIdx = 0;
    int positiveIdx = input.length - 1;
    for(int i = 0; i < input.length ; i++) {
        if(input[i] < 0) {
            output [negativeIdx++] = input[i];
        } else {
            output [positiveIdx--] = input[i];
        }
    }
    System.out.println
    
    (Arrays.toString(output));
    

    Output:

    [-5, -12, 15, 9, 7, 1]
    

提交回复
热议问题