LeetCode 922. Sort Array By Parity II C++ 解题报告

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:

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

解题思想

  1. 使用 2 个 vector 分别保存奇数和偶数,最后依次在合起来。这个方法最直接。
    vector<int> sortArrayByParityII(vector<int>& A) {
        vector<int> odd;
        vector<int> even;
        
        for(auto it = A.begin(); it != A.end(); it++) {
            
            // 偶数
            if(*it % 2 == 0) {
                even.push_back(*it);
            }
            // 奇数
            else {
                odd.push_back(*it);
            }
        }
        
        int i = 0, j = 0, cnt = 0, len = A.size();
        
        A.clear();
        
        for(;cnt<len;cnt++) {
            // 奇数位置
            if(cnt%2 != 0) {
                A.push_back(odd[i++]);
            } 
            // 偶数位置
            else {
                A.push_back(even[j++]);
            }
        }
        
        return A;   
    }
  1. 分别找偶数位置不是偶数,奇数位置不是奇数的地方进行互换。
    vector<int> sortArrayByParityII(vector<int>& A) {
        
        // 检查索引 i 和 A[i] 是否都是偶数
        const auto checkeven = [&A](const int i)->bool {
            return i%2==0 && A[i]%2==0;
        };
        
        // 检查索引 i 和 A[i] 是否都是奇数
        const auto checkodd = [&A](const int i)->bool {
            return i%2!=0 && A[i]%2!= 0;
        };
        
        // 找到索引 i 和A[i] 奇偶数不匹配的位置
        const auto findIndex = [&A](int i, const auto func)->int {
            while(i < A.size() && func(i) == true) {
                i += 2;
            }
            
            return i;
        };
        
        int even = findIndex(0,checkeven);
        int odd = findIndex(1, checkodd);
        
        while(odd < A.size() && even < A.size()) {
            swap(A[even], A[odd]);
            
            even = findIndex(even, checkeven);
            odd = findIndex(odd, checkodd);
        }
                
        return A;
    }
posted on 2018-10-25 09:36  Haikyuu  阅读(306)  评论(0)    收藏  举报