Huawei machine test: adjust the order of the array so that the odd numbers come before the even numbers

Topic description

Input an array of integers, implement a function to adjust the order of the numbers in the array, so that all odd numbers are in the first half of the array, all even numbers are in the second half of the array, and ensure that odd and odd, even and even numbers are between The relative position remains unchanged .


The implementation is as follows:

method 1:

 
  
//The time complexity is O(n^2), and the space complexity is O(1)
public class Solution { public void reOrderArray(int [] array) { if(array.length<=1){ return; } boolean b=true; while(b){ b=false; for(int i=1; i<array.length; i++){ int a1=array[i-1]%2; int a2=array[i]%2; int temp; if(a1==0 && a2!=0){ temp=array[i-1]; array[i-1]=array[i]; array[i]=temp; b=true; } } } } }
Method 2:

 
  
//Time complexity is O(n), space complexity is O(n)
public class Solution { public void reOrderArray(int [] array) { if(array==null || array.length==0){ return; } int[] res=new int[array.length]; int i=0; for(int j=0; j<array.length; j++){ if((array[j] & 1)!=0){ res[i]=array[j]; i++; } } for(int j=0; j<array.length; j++){ if((array[j] & 1)==0){ res[i]=array[j]; i++; } } for(int j=0; j<array.length; j++){ array[j]=res[j]; } } }


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324644548&siteId=291194637