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; }
四、測試結果
從結果中可以看出,程式碼效果還可以,但肯定還有更有效的解決方法,嘿嘿畢竟是第一遍測試程式,繼續努力哦! (▽)