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 2613
醉梦人生
醉梦人生 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:31

    This solution has O(n) time complexity and O(1) space complexity

    Idea is:

    1. keep track of index of last seen negative element (lastNegIndex).

    2. loop through the array to find negative elements that are preceded by positive element.

    3. If such element is found, right rotate elements between lastNegIndex and current Index by one. Then update lastNegIndex (it will be next index).

    Here is the code:

    public void rightRotate(int[] a, int n, int currentIndex, int lastNegIndex){
        int temp = a[currentIndex];
        for(int i = currentIndex; i > lastNegIndex+ 1; i--){
            a[i] = a[i-1];
        }
        a[lastNegIndex+1] = temp;
    }
    
    public void ReArrange(int[] a, int n){
        int lastNegIndex= -1;
        int index;
    
        if(a[0] < 0)
            lastNegIndex = 0;
    
        for(index = 1; index < n; index++){
             if (a[index] < 0 && a[index - 1] >= 0) {
                 rightRotate(a, n, index, lastNegIndex);
                 lastNegIndex = lastNegIndex + 1;
             }
        }
    }
    

提交回复
热议问题