第一种解法:
class Solution {
public int[] exchange(int[] nums) {
int[] res = new int[nums.length];
int left = 0;
int right = nums.length - 1;
for (int num : nums) {
//重点这下面这行
if ((num&1)== 0) {
res[right--] = num;
} else {
res[left++] = num;
}
}
return res;
}
}
1ms 48.1mb
第二种解法:不用位运算符
class Solution {
public int[] exchange(int[] nums) {
int[] res = new int[nums.length];
int left = 0;
int right = nums.length - 1;
for (int num : nums) {
//重点这下面这行
if (num%2 == 0) {
res[right--] = num;
} else {
res[left++] = num;
}
}
return res;
}
}
2ms 48mb
所以,能用位运算就用位运算