티스토리 뷰

Question

중복 원소 없애기

 

정렬되어 있지 않은 연결 리스트가 주어졌을 때 이 리스트에서 중복되는 원소를 제거하는 코드를 작성하라.


Solution

가능한 최선의 수행 시간(Best Conceivable Runtime(BCR)

  • 모든 리스트의 요소들을 다 확인해봐야 하기 때문에 리스트의 최대길이를 n이라 했을 때 O(n)이다.

고려사항

  • 리스트 원소의 자료형을 int 타입으로 가정한다. 

Solution1 (Bruth Force)

가장 간단한 방법이다. 첫 요소부터 순차적으로 탐색하며 같은 원소가 있으면 연결해주는 방식이다. 이 방식은 버퍼를 사용하지 않지만, 공간 복잡도에서 이득이 있다. 

void solution(ListNode* head) {
    while(head !=NULL){
        ListNode* copy = head;
        while (copy != NULL) {
            int check_val = copy->val;

            if(copy->next->val == check_val) copy->next = copy->next->next;
            else copy = copy->next;
        }
    }
}
  • Time complexity : O(n²) 
  • Space Complexity : O(1) 

Solution2

원소를 hash에 넣어두고, 이미 hash table에 있는 원소면 건너뛰는 방식이다. 이 방식은 hash를 저장하기 위한 공간이 필요하기 때문에 O(n)이다.

void solution(ListNode* head) {
    set<int> my_set;
    my_set.insert(head->val);

    while (head->next != NULL) {
        if (my_set.find(head->next->val) != my_set.end()) {
            head->next = head->next->next;
        }
        else {
            my_set.insert(head->next->val);
            head = head->next;
        }
    }
}
  • Time complexity : O(n) 
  • Space Complexity : O(리스트의 유니크 한 숫자의 개수) == O(n)

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

[C++] LeetCode : Search in Rotated Sorted Array  (0) 2022.07.27
[C++] LeetCode : Search a 2D Matrix II  (0) 2022.07.26
[C++] LeetCode : Search for a Range  (0) 2022.07.20
[C++] LeetCode : Find Peak Element  (0) 2022.07.19
[C++] LeetCode : 3sum  (0) 2022.07.18
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함