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 2523
醉梦人生
醉梦人生 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:28

    A simple and easy solution which works in O(n) time complexity.

        int left = 0;
        int right = arr.length - 1;
    
        while (left < right) {
    
            while (arr[left] >= 0) {
                left++;
            }
    
            while (arr[right] < 0) {
                right--;
            }
    
            if (left < right) {
                ArrayUtility.swapInArray(arr, left, right);
        }
    
        ArrayUtility.printArray(arr);
    

提交回复
热议问题