파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 5. 3. 23:45

https://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

음.. 이게 제대로 푼 게 맞나 싶을 정도로 좀 애매했다.
일단 list를 정렬한 후, 정렬된 list와 원래 list를 비교해서 시작점과 끝점을 구해서 정렬이 필요한 구간을 구하면 된다.

list를 정렬하지 않고 하는 방법도 있긴 한데.. 난 좀 더 간단한 방법을 풀어봤다.

class Solution:
    def findUnsortedSubarray(self, nums: List[int]) -> int:
        example = sorted(nums)
        l = len(nums)
        start, end = 0, l
        
        for i in range(l):
            if example[i] != nums[i]:
                start = i
                break
        
        for i in range(l-1, -1, -1):
            if example[i] != nums[i]:
                end = i
                break
        
        if start == 0 and end == l:
            return 0
        
        return end - start + 1

 

반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.05.05
Today's Challenge  (0) 2022.05.04
Today's Challenge  (0) 2022.05.02
Today's Challenge  (0) 2022.05.01
Today's Challenge  (0) 2022.04.30
Comments