LeetCode day 1

class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& nums) {
        int n = nums.size();
        vector<int> even; // 存储偶数
        vector<int> odd;  // 存储奇数

        // 将奇数和偶数分别放入对应的数组
        for (int num : nums) {
            if (num % 2 == 0) {
                even.push_back(num);
            } else {
                odd.push_back(num);
            }
        }

        vector<int> result(n);

        // 从奇数数组和偶数数组中交替取出元素
        for (int i = 0; i < n; ++i) {
            if (i % 2 == 0) {
                result[i] = even.back();
                even.pop_back();
            } else {
                result[i] = odd.back();
                odd.pop_back();
            }
        }

        return result;
    }
};

 方法二:

class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& nums) {
        int n = nums.size();
        int evenIdx = 0; // 偶数索引
        int oddIdx = 1;  // 奇数索引

        while (evenIdx < n && oddIdx < n) {
            while (evenIdx < n && nums[evenIdx] % 2 == 0) {
                evenIdx += 2; // 找到下一个偶数位上为奇数的索引
            }
            while (oddIdx < n && nums[oddIdx] % 2 == 1) {
                oddIdx += 2; // 找到下一个奇数位上为偶数的索引
            }

            if (evenIdx < n && oddIdx < n) {
                swap(nums[evenIdx], nums[oddIdx]); // 交换不满足条件的元素
            }
        }

        return nums;
    }
};

 

posted @ 2023-08-21 17:06  芜湖大厨师  阅读(6)  评论(0编辑  收藏  举报