aboutsummaryrefslogtreecommitdiff
path: root/other/sort_array_parity.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/sort_array_parity.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/sort_array_parity.cpp')
-rw-r--r--other/sort_array_parity.cpp46
1 files changed, 46 insertions, 0 deletions
diff --git a/other/sort_array_parity.cpp b/other/sort_array_parity.cpp
new file mode 100644
index 0000000..33f02b1
--- /dev/null
+++ b/other/sort_array_parity.cpp
@@ -0,0 +1,46 @@
+#include "leetcode.h"
+
+class Solution {
+public:
+ vector<int> sortArrayByParity(vector<int> &nums) {
+ /*
+ * important to assign vector values first:
+ * vector... var(size, vals)
+ */
+ vector<int> ans(nums.size(), 0);
+
+ /*
+ * start at first element (0)
+ * end at "last" element minus 1
+ * because arrays initialize at 0
+ */
+ int start = 0, end = nums.size() - 1;
+
+ for (int i = 0; i < nums.size(); i++) {
+ if (nums[i] % 2 == 1)
+ /*
+ * odd
+ * assign "last" array value to current nums value
+ * and incrementally decrease end when necessary
+ */
+ ans[end--] = nums[i];
+ else
+ /*
+ * even
+ * assign "first" array value to current nums value
+ * and incrementally increase start when necessary
+ */
+ ans[start++] = nums[i];
+ }
+ return ans;
+ }
+};
+
+int main() {
+ vector<int> nums = {3, 1, 2, 4};
+ Solution obj;
+ for (int i = 0; i < nums.size(); i++)
+ cout << nums[i] << ' ';
+ cout << endl;
+ obj.sortArrayByParity(nums);
+}