一、二次遍历+额外空间
解题思路
1、先创建一个数组result存放结果
2、第一次循环,先将偶数放进result
3、第二次循环,再将奇数跟在偶数后面
时间:1ms 空间42.1MB
代码
class Solution {
public int[] sortArrayByParity(int[] nums) {
int ans = 0;
int[] result = new int[nums.length];
for (int num : nums) {
if (num % 2 == 0) {
result[ans++] = num;
}
}
for (int num : nums) {
if (num % 2 == 1) {
result[ans++] = num;
}
}
return result;
}
}
二、一次遍历+额外空间
解题思路
1、先创建一个数组result存放结果
2、循环,是偶数则放进result的前面,奇数则放在后面
时间:0ms 空间42.3MB
代码
class Solution {
public int[] sortArrayByParity(int[] nums) {
int[] result = new int[nums.length];
int left = 0, right = nums.length - 1;
for (int num : nums) {
if (num % 2 == 0) {
result[left++] = num;
} else {
result[right--] = num;
}
}
return result;
}
}
三、原地一次遍历
解题思路
1、双指针
2、前后同时判断是否为奇数或偶数
时间:1ms 空间:41.8MB
代码
class Solution {
public int[] sortArrayByParity(int[] nums) {
int i=0,j=nums.length-1;
while(i<=j){
//前奇后偶,交换
if(nums[i]%2!=0&&nums[j]%2==0){
int temp=nums[i];
nums[i++] = nums[j];
nums[j--] = temp;
}
//前偶后偶,前指针后移
else if(nums[i]%2==0 && nums[j]%2==0){
i++;
}
//前奇后奇,后指针前移
else if(nums[i]%2!=0 && nums[j]%2!=0){
j--;
}
//前偶后奇,不变
else{
i++;
j--;
}
}
return nums;
}
}