From 599532847a3652e4c47af0ff1131c20380427be3 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Mon, 3 Apr 2023 23:47:24 +0800 Subject: [PATCH] add: 230403-CN --- cpp/2304/230403-CN.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 cpp/2304/230403-CN.cpp 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; + } +};