[LeetCode#15] 3Sum

2024. 7. 23. 18:10·Algorithm/문제풀이

❒ Description


 

제목 3Sum
링크 https://leetcode.com/problems/3sum/description/
자료구조 선형 자료구조
시간복잡도 Two Pointer 풀이 - O(n²)

 

선형 자료구조 문제로, two pointer 알고리즘을 사용하여 해결할 수 있는 문제.

이 문제는 중복 값에 대한 적절한 처리를 해줘야 하는 점이 까다로웠다.

 

❒ Solution


public static List<List<Integer>> solve(int[] nums) {
    int left, right, total;
    List<List<Integer>> res = new ArrayList<>();
    Arrays.sort(nums);
    for (int i = 0; i < nums.length -2; i++) {
        // 중복된 값 건너뛰기
        if (i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        left = i + 1;
        right = nums.length - 1;
        while (left < right) {
            total = nums[i] + nums[left] + nums[right];
            if (total > 0) {
                right --;
            } else if (total < 0) {
                left ++;
            } else {
                res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                // 중복된 값 건너 뛰기, 이 처리를 하지 않으면 같은 정답이 주번 나올 수 있다.
                while (left < right && nums[left] == nums[left + 1]) {
                    left ++;
                }
                while (left < right && nums[right] == nums[right - 1]) {
                    right --;
                }
                left ++;
                right --;
            }
        }
    }
    return res;
}

 

이 문제는 Two Pointer 알고리즘을 통해서 해결할 수 있다.

  1. 중복 값 예외 작업을 해준다.
  2. 우선 Two Pointer 알고리즘을 위해 nums를 정렬해준다.
  3. left와 right pointer를 설정해준다.
  4. 각 pointer를 조건에 따라 이동 시킨다.
    • 여기서는 합이 0보다 작을 경우 left pointer를, 0 보다 클 경우에는 right pointer를 이동시킨다.
  5. 중복갑 예외 작업을 해준다.
  6. 원하는 결과가 나온경우 left, right pointer를 각각 한 칸씩 이동한다.

그리고 위 코드의 시간 복잡도는 O(n²) 이다.

  • 입력 받은 배열을 정렬하는데 O(nlogn)
  • for문과 while문이 중첩으로 있기 때문에 O(n²)

'Algorithm > 문제풀이' 카테고리의 다른 글

[LeetCode#234] Palindrome Linked List  (0) 2024.07.24
[LeetCode#121] Best Time to Buy and Sell Stock  (0) 2024.07.24
[LeetCode#238] Product of Array Except Self  (0) 2024.07.23
[LeetCode#42] Trapping Rain Water  (0) 2024.07.23
[LeetCode#1] Two Sum  (0) 2024.07.22
'Algorithm/문제풀이' 카테고리의 다른 글
  • [LeetCode#121] Best Time to Buy and Sell Stock
  • [LeetCode#238] Product of Array Except Self
  • [LeetCode#42] Trapping Rain Water
  • [LeetCode#1] Two Sum
gilbert9172
gilbert9172
gilbert9172 님의 블로그 입니다.
  • gilbert9172
    バックエンド
    gilbert9172
  • 전체
    오늘
    어제
    • All Categories (167)
      • 우테코 7기 (21)
        • 1주차 (8)
        • 2주차 (5)
        • 3주차 (6)
      • Langauge (4)
        • Java (3)
        • Kotlin (1)
      • Back-End (13)
        • SpringBoot (1)
        • Trouble Shooting (0)
        • Setup & Configuration (1)
        • SQL (3)
        • Redis (8)
      • Architecture (6)
        • Multi Module (1)
        • DDD (5)
      • CS (30)
        • Data Structure (6)
        • Operating System (0)
        • Network (12)
        • Database (10)
        • Design Pattern (2)
      • Algorithm (78)
        • 내용 정리 (18)
        • 문제풀이 (60)
      • DevOps (6)
        • AWS (5)
        • Git (1)
      • Front-End (1)
        • Trouble Shooting (1)
      • Project (6)
        • 페이스콕 (6)
      • Book (1)
        • 이벤트 기반 마이크로서비스 구축 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Two-Pointer
    binarysearch
    부분단조성
    Back-Tracking
    greedy
    sliding-window
    오블완
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
gilbert9172
[LeetCode#15] 3Sum
상단으로

티스토리툴바