본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 581] Shortest Unsorted Continuous Subarray

by m2162003 2020. 10. 11.

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.

 

Example 1:

Input: nums = [2,6,4,8,10,9,15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Example 2:

Input: nums = [1,2,3,4] Output: 0

Example 3:

Input: nums = [1] Output: 0

 

풀이:

- 오름차순으로 소팅한 다음 소팅한 배열과 비교한다.

- start는 처음 인덱스,  end는 마지막 인덱스 이기 때문에 각각 min과 max

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        
        int start = nums.size(), end = 0;
        
        vector<int> copyNums;
        
        for(int i=0; i<nums.size(); i++){
            copyNums.push_back(nums[i]);
        }
        
        sort(copyNums.begin(), copyNums.end());
        
        for(int i=0; i<nums.size(); i++){
            if(copyNums[i] != nums[i]){
                start = min(start, i);
                end = max(end, i);
            }
        }
        
        if(end>start){
            return end-start+1;
        }
        return 0;
    }
};

댓글