1. 程式人生 > >LeetCode周賽#106 Q1 Sort Array By Parity II

LeetCode周賽#106 Q1 Sort Array By Parity II

題目來源:https://leetcode.com/contest/weekly-contest-106/problems/sort-array-by-parity-ii/

問題描述

922. Sort Array By Parity II

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, 

i is odd; and whenever A[i] is even, i is even.

You may return any answer array that satisfies this condition.

 

Example 1:

Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

 

Note:

  1. 2 <= A.length <= 20000
  2. A.length % 2 == 0
  3. 0 <= A[i] <= 1000

------------------------------------------------------------

題意

給定一個長度為n(n是偶數)的數列,有n/2個元素是偶數,n/2個元素是奇數。求數列的一個重排,使得偶數下標的元素都是偶數,奇數下標的元素都是奇數。

------------------------------------------------------------

思路

設定兩個指標i和j分別遍歷數列的奇數下標和偶數下標,如果發現i下標位置和j下標位置下標與元素的奇偶性不同就交換。

以後千萬要注意,“==”“!=”的優先順序比位運算高!!!!!!!!

------------------------------------------------------------

程式碼

class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& A) {
        int i= 0 , j = 1, n = A.size();
        while (i<n && j<n)
        {
            while ((A[i] & 1) == 0)
            {
                i += 2;
            }
            if (i >= n)
            {
                break;
            }
            while ((A[j] & 1) == 1)
            {
                j += 2;
            }
            if (j >= n)
            {
                break;
            }
            swap(A[i], A[j]);
        }
        return A;
    }
};