取两个指针i,j,i从左到右查找偶数,j从右到左查找奇数,将找到的奇数和偶数交换位置。当i、j相遇时,查找结束。
- class Solution {
- public int[] exchange(int[] nums) {
- int len = nums.length;
- int i = 0, j = len-1;
- while(i < j)
- {
- while(nums[i] % 2 == 1 && i < j)
- {
- i++;
- }
- while(nums[j] % 2 == 0 && i < j)
- {
- j--;
- }
- int tmp = nums[i];
- nums[i] = nums[j];
- nums[j] = tmp;
- }
- return nums;
- }
- }