题目:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
双指针
先分为四种情况:
public class Solution {
private int[] nums;
public int[] exchange(int[] nums) {
this.nums = nums;
int len = nums.length;
int right = len - 1;
int left = 0;
while(left < right) {
//左边为偶数,右边为奇数
if ((nums[left]&1) != 1 && (nums[right]&1) == 1) {
swap(left, right);
right--;
left++;
} else if ((nums[left]&1) == 1 && (nums[right]&1) != 1) {
//左边为奇数,右边为偶数
left++;
right--;
} else if ((nums[left]&1) != 1 && (nums[right]&1) != 1) {
right--;
} else {
left++;
}
}
return nums;
}
private void swap(int i, int j) {
int tmp;
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 2, 3, 4};
int[] res = sol.exchange(nums);
for (int i : res) {
System.out.println(i);
}
}
}
改进:
public class Solution {
public int[] exchange(int[] nums) {
int len = nums.length;
int right = len - 1;
int left = 0;
while(left < right) {
while (left < right && (nums[left]&1) == 1) {
left++;
}
while (left < right && (nums[right]&1) != 1) {
right--;
}
if (left < right) {
nums[left] ^= nums[right];
nums[right] ^= nums[left];
nums[left] ^= nums[right];
}
}
return nums;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 2, 3, 4};
int[] res = sol.exchange(nums);
for (int i : res) {
System.out.println(i);
}
}
}
利用快慢指针,慢指针存储偶数,快指针寻找奇数
public class Solution {
public int[] exchange(int[] nums) {
int len = nums.length;
int slow = 0;
int fast = 0;
while(fast <= len - 1) {
if ((nums[fast]&1) == 1) {
if (fast != slow) {
nums[fast] ^= nums[slow];
nums[slow] ^= nums[fast];
nums[fast] ^= nums[slow];
}
slow++;
}
fast++;
}
return nums;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {1, 2, 3, 4};
int[] res = sol.exchange(nums);
for (int i : res) {
System.out.println(i);
}
}
}