leetcode.com/problems/shortest-unsorted-continuous-subarray/
Shortest Unsorted Continuous Subarray - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제:
문자 배열이 주어진다. 이것을 오름차순으로 만들기 위해 수정해야하는 배열의 길이를 구하시오.
즉, 1번 케이스에서 6 4 8 10 9 부분을 오름차순 정렬하면 전체가 오름차순이 된다. 이떄의 길이는 5이므로
5를 리턴한다.
접근법:
정렬, 문자열
풀이:
1) 0번 인덱스에서 nums.length까지 최대값을 탐색한다.
2) 배열끝에서 0번 인덱스까지 최소값을 탐색한다.
0~nums.length를 탐색하면서 최대값보다 작은 부분이 있다. 즉, 정렬이 안 된 부분이다.
예를들어 [6, 4] 부분 [10, 9] 부분이 정렬이 안된 부분이다.
이런 정렬이 잘못된 부분의 index를 저장하는 거다. 9의 index인 5를 저장한다.
최소값 찾는것도 똑같이 진행하면 된다.
마지막에 위의 두 index의 차를 구하면된다.
코드
class Solution {
public int findUnsortedSubarray(int[] nums) {
int max=-Integer.MAX_VALUE;
int min =Integer.MAX_VALUE;
int low = -1;
int high = -1;
int answer = 0;
for(int i=0; i<nums.length; i++){
if(max <= nums[i]){
max = nums[i];
}else{
low = i;
}
}
for(int j=nums.length-1; j>=0; j--){
if(min >= nums[j]){
min = nums[j];
}else{
high = j;
}
}
if(low !=-1 && high != -1)
answer = low- high + 1;
return answer;
}
}
'알고리즘 > 리트코드' 카테고리의 다른 글
leetcode - 350. Intersection of Two Arrays II (0) | 2021.09.17 |
---|---|
329. Longest Increasing Path in a Matrix (0) | 2021.04.10 |
621. Task Scheduler (0) | 2021.04.10 |
리트코드 - 데일리과제(3/30) Russian Doll Envelopes (0) | 2021.03.30 |
리트코드 데일리과제(3/27) - palindromic-substrings (0) | 2021.03.27 |