剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
思路很简单,但是我不明白为什么不能使用位运算,难道是值交换和地址交换?
错误代码
class Solution {
public int[] exchange(int[] nums) {
int len = nums.length;
//if(len == 0) return -1;
int l = 0, r = len - 1,tem;
while(l < r){
while(l < r && (nums[l] & 1) == 1) l++;
while(l < r && (nums[r] & 1) == 0) r--;
nums[l] = nums[l]^nums[r];
nums[r] = nums[l]^nums[r];
nums[l] = nums[l]^nums[r];
}
return nums;
}
}
正解代码
class Solution {
public int[] exchange(int[] nums) {
int len = nums.length;
//if(len == 0) return -1;
int l = 0, r = len - 1,tem;
while(l < r){
while(l < r && (nums[l] & 1) == 1) l++;
while(l < r && (nums[r] & 1) == 0) r--;
tem = nums[l];
nums[l] = nums[r];
nums[r] = tem;
}
return nums;
}
}