21. 調整數組順序使奇數位於偶數前面,雙指針(首尾指針、快慢指針),插入排序,

21. 調整數組順序使奇數位於偶數前面

image.png

思路一:插入排序思想

遍歷數組,當是奇數時就跟前面的偶數列交換位置,直到前面是奇數數組

for (int i = 0; i > nums.length; i--) {
            if (nums[i] % 2 != 0) {
                for (int j = i - 1; j > 0; j--) {
                    if (nums[j] % 2 == 0) {
                        int a = nums[j];
                        nums[j] = nums[j + 1];
                        nums[j + 1] = a;
                    }

                }
            } else {
                break;
            }
        }
        return nums;
    }

思想1.5:新建一個數組來放,前面放奇數後面放偶數

class Solution {
    public int[] exchange(int[] nums) {
        int[] n1 = new int[nums.length];
        int count = 0;
        int k = nums.length-1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i]%2!=0){
                n1[count++] = nums[i];
            }else{
                n1[k--] = nums[i];
            }
        }
        return n1;
    }
}

思想二:兩個數組分別存奇數和偶數,遍歷結束後再將兩個數組拼接起來。

重點注意:ArrayList 轉換 int[]的方式 加強for ,沒有更簡單的了
!!!不能用toArray()方法,由於這個函數返回的是Object[],而不是int[]函數

int count = 0;
 for (Integer e : odd) {
     nums[count++] = e;
        }
 for (Integer e : even) {
     nums[count++] = e;
 }
 return nums;

思想三:雙指針之首尾指針

  • i,j兩個指針分別在頭和尾
    i往移,j往移,
    num[i]是偶數,num[j]則是奇數
    交換偶數num[i]和奇數num[j]。
    直到i==jspa

    int i = 0;
          int j = nums.length - 1;
          while (i < j) {
              while (i < j && (nums[i] & 1) == 1) i++;
              while (i < j && (nums[j] & 1) == 0) j--;
              int temp = nums[i];
              nums[i] = nums[j];
              nums[j] = temp;
          }
          return nums;

思想四:雙指針之快慢指針

  • i,j兩個指針都在頭,
    j表示奇數下次存入的位置,
    i往前遍歷,
    若是是奇數,就跟i交換num值
    直到i=nums.length指針

    int j = 0;
          for (int i = 0; i < nums.length; i++) {
    
              if((nums[i]&1)==1){
                  int temp = nums[i];
                  nums[i] = nums[j];
                  nums[j] = temp;
                  j++;
              }
          }
          return nums;
相關文章
相關標籤/搜索