Description
Partition an integers array into odd number first and even number second.
Example
Given [1, 2, 3, 4]
, return[1, 3, 2, 4]
Challenge
Do it in-place.
Problem solving: Separate the odd and even numbers in an array, separating them in place and not applying for additional space. The idea is to record the last odd-numbered position, which can also be understood as the first of the even numbers. Iterates through an array, and does nothing if the elements in the current array are even numbers. If it is odd, it is exchanged with the number of records until the end of the loop. The code is as follows:
Public classSolution {/** @param nums:an array of integers * @return: Nothing*/ Public voidPartitionarray (int[] nums) { //Write your code here intOdd_index = 0;//last singular value of the latter for(inti = 0; i < nums.length; i++){ inttemp =Nums[i]; if(temp% 2 = = 1){ //if it's an odd numberNums[i] =Nums[odd_index]; Nums[odd_index]=temp; Odd_index++; }Else{ //I don't do anything. } } }}
373. Partition Array by Odd and even "Lintcode Java"