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 2614
醉梦人生
醉梦人生 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

    Here is a constriant version of O(n) time O(1) space solution, it assume maxValue*(maxValue+1) is less than Integer.MAX_VALUE, where maxValue is the result of maxmum value minus minmum value in the array. It utilize the original array as the temporary array to store the result.

    public static void specialSort(int[] A){
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        for(int i=0; i max)
                max = A[i];
            if(A[i] < min)
                min = A[i];
        }
        //Change all values to Positive
        for(int i=0; i (-min))
                A[currPositiveIndex++] += (A[i]%newMax)*newMax;
        //Recover to original value 
        for(int i=0; i

提交回复
热议问题