15. 3Sum

2024. 10. 5. 18:13·Algorithm/LeetCode

문제 링크

https://leetcode.com/problems/3sum/description/

 

해결 1.

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int n= nums.length;
        List<List<Integer>> answer=new ArrayList<>();
        //중복을 방지하고자 임시로 사용할 Set을 선언하였다.
        Set<List<Integer>> temp=new HashSet<>();
         // 배열을 먼저 정렬하여 중복 및 순서 문제를 해결
        Arrays.sort(nums);
        for(int i=0;i<n;i++) {
            int target = 0-nums[i];
            // 공간복잡도: O(n)
            // 입력 배열의 길이와 비례해서 증가
            Set<Integer> set = new HashSet<>();
            for(int j=i+1;j<n;j++) {
                int composition = target-nums[j];
                if(set.contains(composition)) {
                    List<Integer> triplet = Arrays.asList(nums[i], nums[j], composition);
                    // 서로 다른 배열에 동일한 요소들이 포함되어 있어도 요소의 순서가 다르면 서로 다른 값으로 
                    // 처리하기 때문에 배열을 정렬 후 Set에 추가하였다.
                    Collections.sort(triplet);
                    temp.add(triplet);
                }
                    
                
                set.add(nums[j]);
            }
        }
        //Set의 값들을 List에 추가
        answer.addAll(temp);
        return answer;
    }
}

- 시간 복잡도: O(n^2)

- 공간 복잡도: O(n)

 

해결 2.

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> answer = new ArrayList<>();
        int n=nums.length;
        Arrays.sort(nums);
        for(int i=0;i<n-2;i++) {
            int left=i+1;
            int right=n-1;

            //중복 처리를 방지
            if(i>0 && nums[i]==nums[i-1])
                continue;

            while(left<right) {
                

                int sum = nums[i]+nums[left]+nums[right];
                if(sum==0) {
                    answer.add(List.of(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+=1;
                    right-=1;
                }
                else if(sum<0) {
                    left+=1;
                }
                else {
                    right-=1;
                }
            }
        }
        return answer;
    }
}

- 시간 복잡도: O(n^2)

- 공간 복잡도: O(1)

'Algorithm > LeetCode' 카테고리의 다른 글

452. Minimum Number of Arrows to Burst Balloons  (0) 2024.10.16
417. Pacific Atlantic Water Flow  (0) 2024.10.14
207. Course Schedule  (0) 2024.10.13
133. Clone Graph  (0) 2024.10.11
11. Container With Most Water  (0) 2024.10.10
'Algorithm/LeetCode' 카테고리의 다른 글
  • 417. Pacific Atlantic Water Flow
  • 207. Course Schedule
  • 133. Clone Graph
  • 11. Container With Most Water
사랑우주인
사랑우주인
  • 사랑우주인
    lovelyAlien
    사랑우주인
  • 전체
    오늘
    어제
  • 글쓰기
    관리
    • 분류 전체보기 (209)
      • Programming (4)
        • Spring (28)
        • Java (46)
        • JPA (2)
        • 디자인 패턴 (5)
        • 개발&아키텍처 (0)
      • Network (14)
      • OS (19)
      • Database (1)
      • Kubernetes (0)
      • Kafka (2)
      • Algorithm (49)
        • BaekJoon (1)
        • Programmers (19)
        • Algorithm (5)
        • Socar (2)
        • LeetCode (19)
      • Interview (2)
      • Issues (2)
      • DotJoin (1)
      • Git (4)
      • 독서 (3)
      • 끄적끄적 (1)
      • 외부활동 (26)
        • 항해플러스 (2)
        • JSCODE 네트워크 (19)
        • JSCODE 자바 (5)
      • SQL (0)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    lower bounded wildcards
    runner 기법
    Thread
    제네릭
    트랜잭션
    LinkedList
    AuthenticationSuccessHandler
    Oauth2
    BFS
    Generic
    준영속 엔티티
    pacific atlantic water flow
    Reorder List
    clone graph
    추상화 클래스
    @JsonNaming
    wildcards
    minimum number of arrows to burst balloons
    Process
    @JsonProperty
    algorithm
    OS
    RR
    디자인 패턴
    socar
    fcfs
    운영체제
    rotting oranges
    Climbing Stairs
    JSCode
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.1
사랑우주인
15. 3Sum
상단으로

티스토리툴바