[LeetCode] Remove Duplicates from Sorted array #26

이지성·2024년 2월 4일

코딩테스트

목록 보기
3/8

문제 링크 : https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/


1. Constraints (제한 사항)

  • 알고리즘 문제와 요구와 제한사항

문제

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.


Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

입력

nums: an integer array

제한

  • 11 <= nums.length <= 3×1043 \times 10^4
  • -100100 <= nums[i] <= 100100
  • nums is sorted in non-decreasing order.

나의 생각

  1. 모든 자료형은 int
  2. 원소가 없는 배열이 입력될 수도 있다.

2. Ideas (문제 풀이 방식)

  • 문제를 해결할 수 있는 방법 (최대 3개) + 시간/공간 복잡도

(1) 브루트포스 알고리즘

: cur, k를 이용한다.
반복문으로 첫번째 원소를 제외하고 순회하는데,
이전에 있는 원소와 같으면 지나가고
다른 원소가 나오면 cur을 현재 원소로 바꾸고,
nums[k]에 지금 수를 저장하고, k에 1을 더한다.

배열이 없는 경우에는 반복문을 순회할 수 없으므로 0을 return한다.

시간 복잡도 : O(N)
공간 복잡도 : O(1)


3. Code (작성한 코드)

  • 아이디어에서 다룬 내용을 바탕으로 구현한 코드
def removeDuplicates(nums: list[int]) -> int:
	if len(nums) <= 0:
    	return 0

    cur, k = nums[0], 1

    for i in range(1, len(nums)):
        if cur != nums[i]:
            cur = nums[i]
            nums[k] = cur
            k = k + 1

    return k

4. Test cases (테스트케이스)

  • 테스트 케이스에 대해서 고민해보고, 직접 테스트해보기
  • []
  • [1,2,3,4]
  • [1,1,2]
  • [1,1,2,2,3]

: 빈 배열, 겹치지 않는 경우, 한 번 겹치는 경우, 여러 번 겹치는 경우
모두 통과했다.

별로 어렵지 않은 문제라서 쉽게 풀 수 있었다.


Python Tutor

아주 쉽게 이해할 수 있었다.


마무리

하마터면 빈 배열을 놓치고 넘어갈 뻔 했다.
다음부터 주의하도록 하자

profile
FROM NOOBY TO RUBY

0개의 댓글