1. 程式人生 > >LeetCode-Sort Array By Parity

LeetCode-Sort Array By Parity

Description: Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

Example 1:

Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Note:

  • 1 <= A.length <= 5000
  • 0 <= A[i] <= 5000

題意:給定一個一維陣列,將陣列中的偶數移動到陣列的首部,奇數放在陣列的尾部;

解法:我們可以定義兩個變數st和ed,st用於指示從首部開始的遇到的奇數,ed用於指示從尾部開始遇到的偶數,將這兩個位置的元素進行交換,一直重複這個操作知道st > ed,這樣所有的偶數就被交換到了首部,奇數被交換到了尾部;

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int st = 0;
        int ed = A.length
- 1; while (st < ed) { while (st < A.length && A[st] % 2 == 0) st++; while (ed >= 0 && A[ed] % 2 == 1) ed--; if (st >= ed) break; A[st] = A[st] ^ A[ed]; A[ed] = A[st] ^ A[ed]; A[st] = A[st] ^ A[ed];
st++; ed--; } return A; } }