LeetCode-922.按奇偶排序数组II(C++实现)

哈哈又到了练习编程的时候了,学习并快乐着!
一、问题描述
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
题目要求: 给定非负整数的数组A,A中的整数的一半是奇数,一半是偶数。对数组进行排序,以便每当A[i]为奇数时,i为奇数;每当A[i]为偶数时,i为偶数。编写函数,返回满足条件的任意一个数组。
二、思路 先遍历数组A,将A中为奇数的元素放在容器B中,为偶数的元素放在容器C中。当A的索引值i为奇数时,将B中的元素赋给A[i],当A的索引值i为偶数时,将C中的元素赋给A[i],最后函数返回数组A。
三、代码

vector<int> sortArrayByParityII(vector<int>& A)
{
	int len = A.size();
	vector<int>B;//奇数
	vector<int>C;//偶数

	for (int i = 0; i < len; i++)
	{
		if (A[i] % 2 == 0)
			C.push_back(A[i]);
		else
			B.push_back(A[i]);
	}
	int j = 0;
	int k = 0;
	int z = 0;
	while (j < len)
	{
		if (j % 2 == 0)
		{
			A[j] = C[k];
			j++;
			k++;
		}
		else
		{
			A[j] = B[z];
			j++;
			z++;
		}
	}
	return A;
}

四、测试结果
在这里插入图片描述
从结果中可以看出,代码效果还可以,但肯定还有更有效的解决方法,嘿嘿毕竟是第一遍测试程序,继续努力哦! ()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值