双指针
public int[] exchange(int[] nums) { int len = nums.length; int[] res = new int[len]; int j = 0, k = len-1; for (int num : nums) { if ((num & 0x1) == 1) {//奇数 res[j++] = num; }else { res[k--] = num; } } return res; }
方法二:
在原数组上用双指针,并且进行交换
class Solution { public int[] exchange(int[] nums) { int len = nums.length; int i = 0,j = len-1; while(i<j){ if((nums[i]&0x1) != 1 && (nums[j]&0x1) == 1){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } while(i<len && (nums[i]&0x1) == 1){ i++; } while(j>=0 && (nums[j]&0x1) != 1){ j--; } } return nums; } }