Title Description
Enter an array of integers to implement a function that adjusts the order of the numbers in the array so that all the odd digits are placed in the first half of the array, all the even digits are located in the second half of the array, and the relative positions between the odd and odd, even and even, are guaranteed.
Enter a description
Array of integers
Output description
Odd number in the former even after, adjusted array
Problem analysis
Solution one run time: 26ms occupied memory: 526k
Import Java.util.arraylist;import java.util.List; Public class solution { Publicvoid Reorderarray (int []Array) {if(Array. length==0||Array==NULL){return; }List<Integer> oddlist =NewArraylist<integer> ();List<Integer> evenlist =NewArraylist<integer> (); for(int i=0;i<Array. length;i++) {if(Array[i]%2==0) {Evenlist.add (Array[i]); }Else{Oddlist.add (Array[i]); }} oddlist.addall (Evenlist); for(int i=0;i<Array. length;i++) {Array[I] = Oddlist.get (i); } }}
This idea is relatively simple, traversing an array to place the odd and even numbers in two new arrays, and then merge and then assign to the array on the line.
Solution two run time: 27ms occupied memory: 503k
Public classSolution { Public voidReorderarray (int[]Array) {if(Array. length==0||Array==null) {return; } for(intI=0;i<Array. length-1; i++) { for(intj=0;j<Array. length-i-1; j + +) {if(Array[j]%2==0&&Array[j+1]%2==1){inttemp =Array[j];Array[j] =Array[j+1];Array[j+1] = temp; } } } }}
Similar to bubble sort, think of using the array[j+1] array do not cross the border.
[Sword to offer] adjust the array order so that the odd digits are preceded by even numbers