diff --git a/cpp/2304/230403-CN.cpp b/cpp/2304/230403-CN.cpp new file mode 100644 index 0000000..723c025 --- /dev/null +++ b/cpp/2304/230403-CN.cpp @@ -0,0 +1,28 @@ +#include +#include +#include + +/** + * 1053. Previous Permutation With One Swap + * Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap. If it cannot be done, then return the same array. + * Note that a swap exchanges the positions of two numbers arr[i] and arr[j] + */ + +class Solution { +public: + std::vector prevPermOpt1(std::vector arr) { + if (std::is_sorted(arr.begin(), arr.end())) + return arr; + const int n = arr.size(); + for (int i = n - 2; i >= 0; --i) { + if (arr[i] <= arr[i + 1]) + continue; + int j = n - 1; + for (; arr[j] >= arr[i] || arr[j] == arr[j - 1]; --j); + std::swap(arr[i], arr[j]); + return arr; + } + // Should not reach here + return arr; + } +};