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;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 438] Find All Anagrams in a String (0) | 2020.10.12 |
---|---|
[leetcode 448] Find All Numbers Disappeared in an Array (0) | 2020.10.12 |
[leetcode 543] Diameter of Binary Tree (0) | 2020.10.11 |
[leetcode 617] Merge Two Binary Trees (0) | 2020.10.11 |
[leetcode 55] Jump Game (0) | 2020.10.10 |
댓글