Offer surface prove safety questions 21 (java version): adjusted so that the array sequentially in front of even-odd

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91411243

welcome to my blog

Offer surface prove safety questions 21 (java version): adjusted so that the array sequentially in front of even-odd

Title Description

Enter an array of integers, to realize a function to adjust the order of the numbers in the array, such that all the odd part of the front half of the array, is located in the second half of all the even array, and between odd and ensure a relatively even, odd and even the same position.

notes

  • An array of issues, the length of the input array may be zero, this is not abnormal
  • java can function as a parameter in it? (try inner class)

The following code is no guarantee that the relative change between the odd-odd and even-numbered and even,

public class Solution {
    public void reOrderArray(int [] array) {
        // input check
        if(array.length < 1)
            throw new RuntimeException("invalid input");
        // execute
        int pStart = 0;
        int pEnd = array.length - 1;
        while(pStart < pEnd){
            while(pStart < pEnd && array[pStart]%2==1) // 当array[pStart]能够待在数组靠前的部分时,向后移动pStart,直到array[pStart]不能待在数组的靠前部分
                pStart++;
            while(pStart < pEnd && array[pEnd]%2==0) // 当array[pEnd]能够待在数组靠后的部分时,向前移动pEnd,直到array[pEnd]不能待在数组的靠后部分
                pEnd--;
            if(pStart < pEnd){
                int temp = array[pStart];
                array[pStart] = array[pEnd];
                array[pEnd] = temp;
            }
        }
    }
}

Ensure that the code and the relative order between the odd-odd, even-even and

public class Solution {
    public void reOrderArray(int [] array) {
        // input check 其实不用健壮性检查, 数组问题,可以输入长度为0的数组!
        //if(array.length < 1)
         //   return null;
         
        // execute
        int oddCnt =0;
        int evenCnt = 0;
        int[] arrayEven = new int[array.length];
        for(int i=0; i<array.length; i++){
            if(array[i]%2==1)
                array[oddCnt++] = array[i]; 
            else
                arrayEven[evenCnt++] = array[i];
        }
        evenCnt = 0;
        for(int i=oddCnt; i<array.length; i++) // oddCnt是第一个偶数的索引
            array[i] = arrayEven[evenCnt++];
    }
}

image.png

Guess you like

Origin blog.csdn.net/littlehaes/article/details/91411243