The topic is as follows
Enter an integer array and 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, and all even numbers are in the second half of the array.
Example:
Input: nums = [1,2,3,4]
Output: [1,3,2,4]
Note: [3,1,2,4] is also one of the correct answers.
Own algorithm and code
(The algorithm class is correctly executed and submitted, and the memory consumption is high, mainly in the creation of a new array to store data)
- Create a new array
result[]
, and two flagsfirst
andlast
, pointing to result [] in the first0
position, the firstnums.length-1
position. - Traverse the array nums from back to front.
- If nums[i] is an even number, add it to the last position of result[] and move last one position forward, that is
last--
; - If nums[i] is an odd number, add it to the first position of result[] and move last one position back, that is
first++
;
- If nums[i] is an even number, add it to the last position of result[] and move last one position forward, that is
- Then return result[].
public class Solution {
public static int[] exchange(int[] nums) {
int[] result = new int[nums.length];
int first = 0;
int last = nums.length-1;
for (int i = nums.length-1; i >= 0; i--){
if (nums[i]%2 == 0){
result[last] = nums[i];
last--;
}else {
result[first] = nums[i];
first++;
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {
1,2,3,4};
int[] result = exchange(nums);
for (int num : result){
System.out.println(num);
}
}
}
Reference algorithm and code
Double pointer
- Define head pointer
left
and tail pointerright
. - left has been moved to the right until the value it points to is even
- right keeps moving to the left until the value it points to is an odd number
- Exchange
nums[left]
andnums[right]
. - Repeat the above operations until
left==right
.
public class Solution {
public static int[] exchange1(int[] nums) {
int left = 0;
int right = nums.length-1;
int temp;
while (left < right){
if (nums[left]%2 != 0){
//奇数
left++;
continue;
}
if (nums[right]%2 == 0){
//偶数
right--;
continue;
}
temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
return nums;
}
public static void main(String[] args) {
int[] nums = {
1,2,3,4};
int[] result = exchange1(nums);
for (int num : result){
System.out.println(num);
}
}
}