905. Sort Array By Parity

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

双指针,右侧指针之后存放奇数项。
当左侧指针的元素为奇数时,交换left和right上的元素。然后将右侧指针左移。
当左侧指针的元素为偶数时,左侧指针左移。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
int[] arr;
public int[] sortArrayByParity(int[] nums) {
arr = nums;
int left = 0;
int right = nums.length-1;

while(left < right){
if(nums[left] % 2 == 1){
swap(left, right);
right--;
}
else{
left++;
}
}
return arr;
}

private void swap(int left, int right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}
Author

Xander

Posted on

2022-05-02

Updated on

2022-05-01

Licensed under

Comments