aboutsummaryrefslogtreecommitdiffstats
path: root/581/main.cpp
blob: 7aac338fca51e63f4280bf532eebe7d60b81f7d7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "header.hpp"
#include <algorithm>

class Solution {
public:
  static int findUnsortedSubarray(std::vector<int> &nums) {
    std::vector<int> nums_copy;
    nums_copy.resize(nums.size());
    std::copy(nums.begin(), nums.end(), nums_copy.begin());
    std::sort(nums_copy.begin(), nums_copy.end());
    int l = 0;
    int n = nums.size() - 1;
    bool begin = 0;
    bool end = 0;
    while (n > l) {
      if (nums_copy[l] == nums[l]) {
        l++;
      } else {
        begin = true;
        break;
      }
    }
    while (n > l) {
      if (nums_copy[n] == nums[n]) {
        n--;
      } else {
        end = true;
        break;
      }
    }
    if (end || begin)
      return n - l + 1;
    else
      return 0;
  }
};

int main(int argc, char **argv) {
  std::vector<int> nums1 = {2, 6, 4, 8, 10, 9, 15};
  std::vector<int> nums2 = {1, 2, 3, 4};
  std::cout << Solution::findUnsortedSubarray(nums1) << std::endl;
  std::cout << Solution::findUnsortedSubarray(nums2) << std::endl;
  return 0;
}