用chrono庫寫個方便使用的計時器
阿新 • • 發佈:2021-06-18
描述
輸入一個整數陣列,實現一個函式來調整該陣列中數字的順序,使得所有的奇數位於陣列的前半部分,所有的偶數位於陣列的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。
演算法
題目要求圖解:
具體的做法就是把每個數加入符合條件的陣列,如下圖,橙色代表奇數陣列,綠色代表偶數陣列,最後再合併兩個陣列。
因為我們是按照從左到右的順序訪問每個元素,容易證明奇數元素、偶數元素之間的相對位置是可以保證的,實現的程式碼如下:
// c++ class Solution { public: vector<int> reOrderArray(vector<int>& array) { // write code here vector<int> res(array.size(), 0); int idx = 0; for (int u : array) if (u % 2) res[idx++] = u; for (int u : array) if (u % 2 == 0) res[idx++] = u; return res; } };
# python3
class Solution:
def reOrderArray(self , array ):
# write code here
res = []
for each in array:
if each % 2: res.append(each)
for each in array:
if not each % 2: res.append(each)
return res
因為兩次遍歷陣列時間複雜度是 O(n),使用了一個額外陣列空間複雜度是 O(n)