From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/next_permutation.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 other/next_permutation.cpp (limited to 'other/next_permutation.cpp') diff --git a/other/next_permutation.cpp b/other/next_permutation.cpp new file mode 100644 index 0000000..95e70f4 --- /dev/null +++ b/other/next_permutation.cpp @@ -0,0 +1,37 @@ +#include +#include +using namespace std; + +class Solution { +public: + void nextPermutation(vector &nums) { + int i = nums.size() - 2; + while (i >= 0 && nums[i + 1] <= nums[i]) + i--; + if (i >= 0) { + int j = nums.size() - 1; + while (nums[j] <= nums[i]) + j--; + swap(nums, i, j); + } + reverse(nums, i + 1); + } + +private: + void reverse(vector &nums, int start) { + int i = start, j = nums.size() - 1; + while (i < j) { + swap(nums, i, j); + i++; + j--; + } + } + + void swap(vector &nums, int i, int j) { + int temp = nums[i]; + nums[i] = nums[j]; + nums[j] = temp; + } +}; + +int main() {} -- cgit v1.2.3