From e56c314d023012153c89eaa649ac87a31fe8f600 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Wed, 4 May 2022 18:09:06 +0800 Subject: [PATCH] add: 220503 [cpp] --- cpp/2205/220503.cpp | 65 +++++++++++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220503.cpp diff --git a/cpp/2205/220503.cpp b/cpp/2205/220503.cpp new file mode 100644 index 0000000..bada45b --- /dev/null +++ b/cpp/2205/220503.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +#include + +/** + * 581. Shortest Unsorted Continuous Subarray + * Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. + * Return the shortest such subarray and output its length. + */ + +class Solution { +public: + static int findUnsortedSubarray(const std::vector& n) { + int x = n.size(), f = 0, r = x - 1; + int maxF = n[f], minF = n[f], maxR = n[r], minR = n[r]; + while (f + 1 < x && n[f] <= n[f + 1]) { + ++f; + maxF = std::max(n[f], maxF); + minF = std::min(n[f], minF); + } + while (r - 1 > 0 && n[r - 1] < n[r]) { + --r; + maxR = std::max(n[r], maxR); + minR = std::min(n[r], minR); + } + + // todo: SegTree + // Use segment tree to implement makes it O(n). + } +}; + +class SolutionOld { +public: + static int findUnsortedSubarray(const std::vector& n) { + if (std::is_sorted(n.begin(), n.end())) + return 0; + + std::multiset s(n.begin(), n.end()); + + int f = 0, r = n.size() - 1; + while (f < r) { + bool m = false; + if (n[f] == *s.begin()) { + s.erase(s.begin()); + ++f; + m = true; + } + auto last = std::prev(s.end()); + if (n[r] == *last) { + s.erase(last); + --r; + m = true; + } + if (!m) + break; + } + return r - f + 1; + } +}; + +int main() { + std::cout << Solution::findUnsortedSubarray({1,3,2,3,3}); + return 0; +} diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index bcb81a9..1a74bc6 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220503-CN.cpp) +ADD_EXECUTABLE(2204 220503.cpp)