哈哈又到了练习编程的时候了,学习并快乐着!
一、问题描述
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;
}
四、测试结果
从结果中可以看出,代码效果还可以,但肯定还有更有效的解决方法,嘿嘿毕竟是第一遍测试程序,继续努力哦! (▽)