20.11.12 leetcode922

题目链接:https://leetcode-cn.com/problems/sort-array-by-parity-ii/

题意:给你一个数组,保证一半奇数,一半偶数,将数组排成奇数下标放奇数,偶数下标放偶数。

分析:太简单了不提了,注意一点的就是判断A[i]%2为0的时候不能前面直接加!,要么括起来要么老实A[i]%2==0吧。

class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& A) {
        int sz=A.size();
        for(int i=0;i<sz-1;i++){
            if(i%2){
                if(A[i]%2)continue;
                else {
                    for(int j=i+1;j<sz;j++){
                        if(A[j]%2){
                            swap(A[i],A[j]);
                            break;
                        }
                    }
                }
            }
            else{
                if(A[i]%2==0)continue;
                else {
                    for(int j=i+1;j<sz;j++){
                        if(A[j]%2==0){
                            swap(A[i],A[j]);
                            break;
                        }
                    }
                }
            }
        }
        return A;
    }
};
原文地址:https://www.cnblogs.com/qingjiuling/p/13964167.html