-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0905-Sort_Array_by_Parity.cpp
More file actions
88 lines (78 loc) · 1.83 KB
/
0905-Sort_Array_by_Parity.cpp
File metadata and controls
88 lines (78 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*******************************************************************************
* 0905-Sort_Array_by_Parity.cpp
* Billy.Ljm
* 28 September 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/sort-array-by-parity/
*
* Given an integer array nums, move all the even integers at the beginning of
* the array followed by all the odd integers.
*
* Return any array that satisfies this condition.
*
* ===========
* My Approach
* ===========
* We can iterate through the array, swapping any even integers to the front
* and odd integers to the back.
*
* This has a time complexity of O(n), and a space complexity of O(1), where n
* is the size of the array.
******************************************************************************/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (const auto elem : v) {
os << elem << ",";
}
if (v.size() > 0) os << "\b";
os << "]";
return os;
}
/**
* Solution
*/
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& nums) {
int front = 0, back = nums.size() - 1; // index of sorted sections
while (front != back) {
// keep even integers at front
if (nums[front] % 2 == 0) {
front++;
}
// swap odd integers to back
else {
swap(nums[front], nums[back]);
back--;
}
}
return nums;
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
vector<int> nums;
// test case 1
nums = { 3,1,2,4 };
std::cout << "sortArrayByParity(" << nums << ") = ";
std::cout << sol.sortArrayByParity(nums) << std::endl;
// test case 2
nums = { 0 };
std::cout << "sortArrayByParity(" << nums << ") = ";
std::cout << sol.sortArrayByParity(nums) << std::endl;
return 0;
}