joonbread의 등록된 링크

키자드에 등록된 총 1673개의 포스트를 확인하실 수 있습니다.

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 9번_이웃한 칸

JAVA_프로그래머스_PCCE 기출문제 9번_이웃한 칸 풀이 class Solution { // 상하좌우 방향 private static final int[] dw = {-1, 1, 0, 0}; private static final int[] dh = {0, 0, -1, 1}; public int solution(String[][] board, int h, int w) { // 특정 칸 기준으로 상하좌우 값을 비교한다. String targetColor = board[h][w]; // 기준 칸 색상 int cnt = 0; // 이웃 칸 개수 세기 int rows = board.length; // h int cols = board[0].length; // w // 상하좌우 인접 칸 검사 for(int i = 0; i < 4; i++){ int newRow = h + dw[i]; int newCol = w + dh[i]; // 범위 체크 if(newRow >= 0 && newRow <

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 10번_데이터 분석

JAVA_프로그래머스_PCCE 기출문제 10번_데이터 분석 풀이 import java.util.Arrays; class Solution { public int[][] solution(int[][] data, String ext, int val_ext, String sort_by) { // 특정 값 기준 인덱스 추출 int extIndex = getIndex(ext); int sortIndex = getIndex(sort_by); // 필터, 오름차순 정렬, 배열 변환 수행 return Arrays.stream(data).filter(row -> row[extIndex] < val_ext) // 조건 필터링 .sorted((a, b) -> Integer.compare(a[sortIndex], b[sortIndex])) // 오름차순 정렬 .toArray(int[][]::new); // int[][] 배열로 변환 } // 열 이름을 배열 인덱스로 변환 private int getInde

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 10번_공원

JAVA_프로그래머스_PCCE 기출문제 10번_공원 풀이 import java.util.Arrays; class Solution { public int solution(int[] mats, String[][] park) { // 돗자리 크기를 오름차순 정렬 Arrays.sort(mats); int rows = park.length, cols = park[0].length, size = 0; // 큰 돗자리부터 차례대로 탐색 for(int i = mats.length - 1; i >= 0; i--){ size = mats[i]; // 돗자리 위치 탐색 for(int j = 0; j <= rows - size; j++){ for(int k = 0; k <= cols - size; k++){ // 가능한 가장 큰 크기 바로 반환 if(place(j, k, size, park)) return size; } } } // 모든 돗자리 안되면 -1 반환 return -1; } // 돗자리를 r,

Naver Blog

JAVA_LeetCode 343_Integer Break

JAVA_LeetCode 343_Integer Break 풀이 class Solution { public int integerBreak(int n) { // dp[i]는 정수 i를 쪼갰을 때 최대 곱을 저장하는 배열 int[] dp = new int[n + 1]; dp[1] = 1; // 초기 값 설정 // 2부터 n까지 모든 수에 대해 최대 곱을 계산 for(int i = 2; i <= n; i++){ // i를 j와 i - j로 나눔, j는 1부터 i - 1까지 변화 for(int j = 1; j < i; j++){ // 최대값을 dp[i]에 저장 // 1) i - j를 더 쪼갤 경우: dp[i - j] * j // 2) i - j를 더 쪼개지 않을 경우: (i - j) * j dp[i] = Math.max(dp[i], Math.max(dp[i - j] * j, (i - j) * j)); } } return dp[n]; // n을 쪼갰을 때의 최대 곱 출력 } } dp 풀이, 2

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 6번 가채점

JAVA_프로그래머스_PCCE 기출문제 6번 가채점 풀이 class Solution { public String[] solution(int[] numbers, int[] our_score, int[] score_list) { int num_student = numbers.length; String[] answer = new String[num_student]; for (int i = 0; i < num_student; i++) { if (our_score[i] == score_list[numbers[i] - 1]) { answer[i] = "Same"; } else { answer[i] = "Different"; } } return answer; } } 값 비교 시 인덱스 값 오류 확인 * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/250128

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 6번 물 부족

JAVA_프로그래머스_PCCE 기출문제 6번 물 부족 풀이 class Solution { public int solution(int storage, int usage, int[] change) { int total_usage = 0; for(int i=0; i<change.length; i++){ // usage += usage * (change[i] / 100); 오류뜸 usage = usage + (usage * change[i] / 100); total_usage += usage; if(total_usage > storage){ return i; } } return -1; } } 자바 연산자 우선순위가 잘 안먹히는 문제같음 * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/340202

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 7번 가습기

JAVA_프로그래머스_PCCE 기출문제 7번 가습기 풀이 class Solution { public int func1(int humidity, int val_set){ if(humidity < val_set) return 3; return 1; } public int func2(int humidity){ if(humidity >= 50) return 0; else if (humidity >= 40) return 1; else if (humidity >= 30) return 2; else if (humidity >= 20) return 3; else if (humidity >= 10) return 4; else return 5; } public int func3(int humidity, int val_set){ if(humidity < val_set) return 1; return 0; } public int solution(String mode_type, int humidity, i

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 7번 버스

JAVA_프로그래머스_PCCE 기출문제 7번 버스 풀이 class Solution { public int solution(int seat, String[][] passengers) { int num_passenger = 0; for(int i=0; i<passengers.length; i++){ num_passenger += func4(passengers[i]); num_passenger -= func3(passengers[i]); } int answer = func1(seat - num_passenger); return answer; } public int func1(int num){ if(0 > num){ return 0; } else{ return num; } } public int func2(int num){ if(num > 0){ return 0; } else{ return num; } } public int func3(String[] station){ int num = 0

Naver Blog

JAVA_LeetCode 328_Odd Even Linked List

JAVA_LeetCode 328_Odd Even Linked List 풀이 class Solution { public ListNode oddEvenList(ListNode head) { // 리스트가 비었거나 노드가 1개인 경우 if(head == null || head.next == null) return head; ListNode odd = head; // 홀수 인덱스 노드를 가리키는 포인터 (첫 번째 노드) ListNode even = head.next; // 짝수 인덱스 노드를 가리키는 포인터 (두 번째 노드) ListNode evenHead = even; // 짝수 리스트의 시작점 저장 (홀수 리스트 뒤에 붙일 예정) // 짝수와 홀수 연결을 교차하면서 반복 while(even != null && even.next != null){ odd.next = even.next; // 현재 홀수 노드 다음을 짝수 다음(다음 홀수) 노드로 연결 odd = odd.next; // 홀수

Naver Blog

JAVA_LeetCode 331_Verify Preorder Serialization of a Binary Tree

JAVA_LeetCode 331_Verify Preorder Serialization of a Binary Tree 풀이 class Solution { public boolean isValidSerialization(String preorder) { String[] nodes = preorder.split(","); // 노드들(숫자 또는 #)을 콤마 기준으로 분리 int slots = 1; // 트리가 가질 수 있는 자식 슬롯 개수, 처음에는 루트 노드 슬롯 1개 // 문자열 상 현재 노드 숫자 여부를 체크한다. for(String node : nodes){ if(slots == 0) return false; slots--; // 노드를 배치하면슬롯 하나 감소 if (!node.equals("#")) slots += 2; // '#'은 null 노드니까 슬롯 증가 없지만 숫자인경우 슬롯을 2 증가 시킴 } return slots == 0; } } 전위 순회 방식, 직렬화된 문자열을

Naver Blog

JAVA_LeetCode 334_Increasing Triplet Subsequence

JAVA_LeetCode 334_Increasing Triplet Subsequence 풀이 class Solution { public boolean increasingTriplet(int[] nums) { // 인덱스, 인덱스 대응 요소값이 점차 증가하는 경우를 찾기 int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; for(int num : nums){ if(num <= first) first = num; else{ // 현 요소값 기준 작거나 같은 수를 찾았을 경우까지를 체크한다. if(num <= second) second = num; else return true; } } return false; } } greedy Algorithm, 투 포인터 방식 배열을 한번 순회하며, 앞서 구한 값을 통해 조건을 갱신해나감 갱신 과정을 통해 항상 최선의 선택을 구하는 점이 greedy Algorithm이라 할 수 있음 * 출처 ht

Naver Blog

h2 db 설치_windows 11 기준

h2 db 설치_windows 11 기준 아래 사이트 접속 https://www.h2database.com/html/main.html H2 Database Engine Download Version 2.4.240 (2025-09-22) Windows Installer (6.7 MB) All Platforms (zip, 9.5 MB) All Downloads Support Stack Overflow (tag H2) Google Group For non-technical issues, use: Features Very fast, open source, JDBC API Embedded and server modes; disk-based or in-memory databases Transaction su... www.h2database.com 2. 윈도우 버전 다운로드 및 설치 설치 시 해당 경로 기억하기 경로 변경 안했을 경우 아래와 같음 3. 설치 후 화면 4. cmd 창 관리자 권한으

Naver Blog

JAVA_LeetCode 337_House Robber III

JAVA_LeetCode 337_House Robber III 풀이 class Solution { // 메모이제이션용 캐시: 각 노드별 [0]: 털지 않았을 때 최대 금액, [1]: 털었을 때 최대 금액 저장 private Map<TreeNode, int[]> memo = new HashMap<>(); public int rob(TreeNode root) { // dfs 결과 배열 반환: result[0] = 안 털었을 때 최대값, result[1] = 털었을 때 최대값 int[] result = dfs(root); // 루트 노드에서 턴 경우와 안 턴 경우 중 최대값 반환 return Math.max(result[0], result[1]); } private int[] dfs(TreeNode node) { // 종료 조건: 노드가 null이면 돈을 훔칠 수 없으므로 0 반환 if (node == null) return new int[2]; // 이미 계산된 노드면 memo에서 재사

Naver Blog

JAVA_LeetCode 341_Flatten Nested List Iterator

JAVA_LeetCode 341_Flatten Nested List Iterator 풀이 public class NestedIterator implements Iterator<Integer> { private Queue<Integer> data = new LinkedList<>(); // 중첩된 정수를 평탄화한 값을 저장하는 큐 public NestedIterator(List<NestedInteger> nestedList) { Recursive(nestedList); } // 재귀 호출로 중첩 리스트를 탐색하며 정수를 큐에 추가 private void Recursive(List<NestedInteger> list) { for(NestedInteger l : list){ if(l.isInteger()) data.add(l.getInteger()); // 노드가 정수면 바로 큐에 삽입 else Recursive(l.getList()); // 리스트면 재귀적으로 다시 탐색 } } @Ove

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 8번_닉네임 규칙

JAVA_프로그래머스_PCCE 기출문제 8번_닉네임 규칙 풀이 class Solution { public String solution(String nickname) { String answer = ""; for(int i=0; i<nickname.length(); i++){ if(nickname.charAt(i) == 'l'){ answer += "I"; } else if(nickname.charAt(i) == 'w'){ answer += "vv"; } else if(nickname.charAt(i) == 'W'){ answer += "VV"; } else if(nickname.charAt(i) == 'O'){ answer += "0"; } else{ answer += nickname.charAt(i); } } while(answer.length() < 4){ answer += "o"; } if(answer.length() > 8){ answer = answer.substring(0

Naver Blog

JAVA_프로그래머스_PCCE 기출문제8번_창고 정리

JAVA_프로그래머스_PCCE 기출문제8번_창고 정리 풀이 class Solution { public String solution(String[] storage, int[] num) { int num_item = 0; String[] clean_storage = new String[storage.length]; int[] clean_num = new int[num.length]; for(int i=0; i<storage.length; i++){ int clean_idx = -1; for(int j=0; j<num_item; j++){ if(storage[i].equals(clean_storage[j])){ clean_idx = j; break; } } if(clean_idx == -1){ clean_storage[num_item] = storage[i]; clean_num[num_item] = num[i]; num_item += 1; } else{ clean_num[clean_idx

Naver Blog

JAVA_프로그래머스_PCCE 기출문제9번_지폐 접기

JAVA_프로그래머스_PCCE 기출문제9번_지폐 접기 풀이 class Solution { public int solution(int[] wallet, int[] bill) { // 먼저 각 영역별 최대, 최소값을 구하고 조건에 부합할때까지 계속해서 나눈다. int answer = 0; int billMin = Math.min(bill[0], bill[1]), billMax = Math.max(bill[0], bill[1]); int walletMin = Math.min(wallet[0], wallet[1]), walletMax = Math.max(wallet[0], wallet[1]); while(true){ // 90도 돌려서 넣을 수 있는 조건 검사 boolean fitsNormal = (billMin <= walletMin && billMax <= walletMax); boolean fitsRotated = (billMin <= walletMax && billMax <= wal

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 1번 출력

JAVA_프로그래머스_PCCE 기출문제 1번 출력 풀이 import java.util.Scanner; public class Solution { public static void main(String[] args) { String msg = "Spring is beginning"; int val1 = 3; String val2 = "3"; System.out.println(msg); System.out.println(val1 + 10); System.out.println(val2 + "10"); } } * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/250133

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 2번 피타고라스의 정리

JAVA_프로그래머스_PCCE 기출문제 2번 피타고라스의 정리 풀이 import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int c = sc.nextInt(); int b_square = (c * c) - (a * a); System.out.println(b_square); } } 피타고라스 공식을 기준으로 해당 공식에 맞춰 풀면 끝 * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/250132

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 1번 문자 출력

JAVA_프로그래머스_PCCE 기출문제 1번 문자 출력 풀이 import java.util.Scanner; public class Solution { public static void main(String[] args) { String message = "Let's go!"; System.out.println("3\n2\n1"); System.out.println(message); } } * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/340207

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 2번 각도 합치기

JAVA_프로그래머스_PCCE 기출문제 2번 각도 합치기 풀이 import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int angle1 = sc.nextInt(); int angle2 = sc.nextInt(); int sum_angle = (angle1 + angle2) % 360; System.out.println(sum_angle); } } 나머지 연산자 확인 문제 * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/340206

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 3번 나이 계산

JAVA_프로그래머스_PCCE 기출문제 3번 나이 계산 풀이 import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int year = sc.nextInt(); String age_type = sc.next(); int answer = 0; if (age_type.equals("Korea")) { answer = 2030 - year + 1; } else if (age_type.equals("Year")) { answer = 2030 - year; } System.out.println(answer); } } * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/250131

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 3번 수 나누기

JAVA_프로그래머스_PCCE 기출문제 3번 수 나누기 풀이 import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int number = sc.nextInt(); int answer = 0; for(int i = 0; i < (number / 2); i++){ answer += number % 100; number /= 100; } System.out.println(answer); } } number의 길이가 10 이하이므로 해당 조건에 맞춰 적용 * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/340205

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 4번 저축

JAVA_프로그래머스_PCCE 기출문제 4번 저축 풀이 import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int start = sc.nextInt(); int before = sc.nextInt(); int after = sc.nextInt(); int money = start; int month = 1; while (money < 70) { money += before; month++; } while (money < 100) { money += after; month++; } System.out.println(month); } } * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/250130

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 4번 병과분류

JAVA_프로그래머스_PCCE 기출문제 4번 병과분류 풀이 import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String code = sc.next(); String lastFourWords = code.substring(code.length()-4, code.length()); if(lastFourWords.equals( "_eye" )){ System.out.println("Ophthalmologyc"); } else if( lastFourWords.equals("head") ){ System.out.println("Neurosurgery"); } else if( lastFourWords.equals("infl") ){ System.out.println("Orthopedics"); } else if(la

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 5번 산책

JAVA_프로그래머스_PCCE 기출문제 5번 산책 풀이 class Solution { public int[] solution(String route) { int east = 0; int north = 0; int[] answer = new int [2]; for(int i=0; i<route.length(); i++){ switch(route.charAt(i)){ case 'N': north++; break; case 'S': north--; break; case 'E': east++; break; case 'W': east--; break; } } answer[0] = east; answer[1] = north; return answer; } } * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/250129

Naver Blog

JAVA_프로그래머스_PCCE 기출문제 5번 심폐소생술

JAVA_프로그래머스_PCCE 기출문제 5번 심폐소생술 풀이 class Solution { public int[] solution(String[] cpr) { int[] answer = {0, 0, 0, 0, 0}; String[] basic_order = {"check", "call", "pressure", "respiration", "repeat"}; for(int i=0; i<cpr.length; i++){ for(int j=0; j<basic_order.length; j++){ if(cpr[i].equals(basic_order[j])){ answer[i] = j + 1; break; } } } return answer; } } 이중 for문 조건과 요소값 초기화 문제 * 출처 https://school.programmers.co.kr/learn/courses/30/lessons/340203

Naver Blog

JAVA_LeetCode 313_Super Ugly Number

JAVA_LeetCode 313_Super Ugly Number 풀이 class Solution { public int nthSuperUglyNumber(int n, int[] primes) { // 중복없이 primes 배열에 있는 소인수만 가진 Super Ugly Number들을 최소값 우선으로 차례대로 생성하기 int[] ugly = new int[n]; // 특정 소수에 포함된 소인수만 가지는 양의 정수(Super Ugly Number)를 담을 배열 ugly[0] = 1; // 첫 번째 슈퍼 어글리 넘버는 1로 초기화 int k = primes.length; // primes 배열 길이 int[] indices = new int[k]; // primes별 곱셈에 사용할 ugly 인덱스 포인터 long[] nextMultiples = new long[k]; // 각 primes * ugly[indices[i]] 결과값(다음 후보값) // 초기 nextMultiples 값 설정:

Naver Blog

JAVA_LeetCode 316_Remove Duplicate Letters

JAVA_LeetCode 316_Remove Duplicate Letters 풀이 class Solution { public String removeDuplicateLetters(String s) { int[] lastIndex = new int[26]; // 각 문자의 마지막 등장 위치 boolean[] visited = new boolean[26]; // 스택 포함 여부 for(int i = 0; i < s.length(); i++) lastIndex[s.charAt(i) - 'a'] = i; StringBuilder stack = new StringBuilder(); // 스택 역할 (문자 추가/제거) for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(visited[c - 'a']) continue; // 이미 포함 시 건너뜀 // 현재 문자보다 큰 문자 중 뒤에 다시 나올 수 있는 문자 제거 while(stack.l

Naver Blog

JAVA_LeetCode 318_Maximum Product of Word Lengths

JAVA_LeetCode 318_Maximum Product of Word Lengths 풀이 class Solution { public int maxProduct(String[] words) { int n = words.length; int maxProduct = 0; int[] bitMasks = new int[n]; // 각 단어 문자 집합 비트마스크 저장 int[] lengths = new int[n]; // 각 단어 길이 저장 // 단어별 비트마스크 계산 for(int i = 0; i < n; i++){ int mask = 0; for(char c : words[i].toCharArray()) mask |= 1 << (c - 'a'); // 해당 문자에 대응되는 비트 세팅 bitMasks[i] = mask; lengths[i] = words[i].length(); } // 단어 쌍별로 중복 문자 없는지 검사 후 최대 곱 계산 for(int i = 0; i < n - 1; i

Naver Blog

JAVA_LeetCode 319_Bulb Switcher

JAVA_LeetCode 319_Bulb Switcher 풀이 class Solution { public int bulbSwitch(int n) { // n이 작은 경우에 대한 빠른 반환 if(n == 0) return 0; // 최대한 빠른 계산을 위해 제곱근을 활용 return (int)Math.sqrt(n); } } 전구 스위치가 작동할때 해당 전구가 켜져있는지 확인하는 문제 확인 해당 문제의 풀이는 마지막 전구의 상태 변화가 홀수인지 확인 9까지 예시표 전구 번호 약수 약수 개수 최종 전구 상태 (켜짐=1, 꺼짐=0) 1 1 1 1 2 1, 2 2 0 3 1, 3 2 0 4 1, 2, 4 3 1 5 1, 5 2 0 6 1, 2, 3, 6 4 0 7 1, 7 2 0 8 1, 2, 4, 8 4 0 9 1, 3, 9 3 1 약수 개수가 홀수인 전구가 켜져있음을 확인 * 출처 https://leetcode.com/problems/bulb-switcher/?envType=problem

Naver Blog

JAVA_LeetCode 322_Coin Change

JAVA_LeetCode 322_Coin Change 풀이 class Solution { public int coinChange(int[] coins, int amount) { // dp 배열은 amount + 1 크기로, dp[i]는 i 금액을 만들기 위해 필요한 최소 동전 개수를 의미 int[] dp = new int[amount + 1]; // dp 배열을 amount + 1로 채움 (amount보다 큰 값으로 초기화하여 나중에 최소값 갱신이 쉽게) Arrays.fill(dp, amount + 1); dp[0] = 0; // 0 금액을 만들기 위한 최소 동전 개수는 0 // 모든 동전 후보에 대해 최소 동전 개수 갱신 for(int i = 1; i <= amount; i++){ for(int coin : coins){ // 현재 금액 i에서 동전 coin을 뺀 금액의 최소 동전 수 + 1과 기존값 중 작은 값을 dp[i]로 저장 if(coin <= i) dp[i] = Math.

Naver Blog

JAVA_LeetCode 324_Wiggle Sort II

JAVA_LeetCode 324_Wiggle Sort II 풀이 class Solution { public void wiggleSort(int[] nums) { int n = nums.length; int[] sorted = nums.clone(); // 입력 배열 복사 Arrays.sort(sorted); // 복사본을 오름차순 정렬 int left = (n - 1) / 2; // 중간값(작은 값들)의 시작 포인터 (왼쪽 부분 끝) int right = n - 1; // 끝에서부터 큰 값들 차례대로 쓸 포인터 (오른쪽 부분 끝) // 인덱스별로 짝수(even)·홀수(odd) 위치에 맞게 값 배치 for(int i = 0; i < n; i++){ // 짝수 인덱스: 작은 값, 홀수 인덱스: 큰 값 nums[i] = (i % 2 == 0) ? sorted[left--] : sorted[right--]; } } } 중복 불가, 투 포인터 이용, 홀/짝수 인덱스를 이용하여 위치별 삽입 이

Naver Blog

JAVA_LeetCode 309_Best Time to Buy and Sell Stock with Cooldown

JAVA_LeetCode 309_Best Time to Buy and Sell Stock with Cooldown 풀이 class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0) return 0; int n = prices.length; int[] buy = new int[n]; // i일 차에 주식을 산 상태에서의 최대 이익 int[] sell = new int[n]; // i일 차에 주식을 판 상태에서의 최대 이익 int[] cooldown = new int[n]; // i일 차에 쿨다운 상태의 최대 이익 buy[0] = -prices[0]; // 첫날 산 경우 sell[0] = 0; // 첫날 팔 수 없음 cooldown[0] = 0; // 첫날 쿨다운 임의로 0 for(int i = 1; i < n; i++){ // buy 상태: 두 가지 경우 중 최대 // 1. 이

Naver Blog

JAVA_LeetCode 310_Minimum Height Trees

JAVA_LeetCode 310_Minimum Height Trees 풀이 class Solution { public List<Integer> findMinHeightTrees(int n, int[][] edges) { // 트리에서 리프를 바깥부터 반복적으로 제거하면서 남은 중심 노드 중 최소 높이의 노드를 찾기(가지 치기) // 노드가 1개뿐이라면 바로 반환 if(n == 1) return Collections.singletonList(0); // 인접 리스트 초기화(각 노드마다 연결된 리스트 생성) List<Integer>[] graph = new ArrayList[n]; for(int i = 0; i < n; i++) graph[i] = new ArrayList<>(); // 각 노드의 간선 수(진입 차수)를 기록할 배열 int[] degree = new int[n]; // edges 배열을 순회하며 연결 및 차수 증가 for(int[] e : edges){ graph[e[0

Naver Blog

JAVA_LeetCode 284_Peeking Iterator

JAVA_LeetCode 284_Peeking Iterator 풀이 class PeekingIterator implements Iterator<Integer> { private Iterator<Integer> iterator; // 원본 이터레이터를 참조 private Integer peekVal; // peek 할 값을 임시 저장 private boolean cached; // peek 값이 이미 캐싱됐는지 여부 체크 public PeekingIterator(Iterator<Integer> iterator) { this.iterator = iterator; this.cached = false; } public Integer peek() { // peek 값이 아직 캐싱되지 않았다면, 다음 값을 미리 저장 if(!cached){ peekVal = iterator.next(); cached = true; } return peekVal; } @Override public Integer

Naver Blog

JAVA_LeetCode 287_Find the Duplicate Number

JAVA_LeetCode 287_Find the Duplicate Number 풀이 class Solution { public int findDuplicate(int[] nums) { // 투 포인터를 이용, 싸이클을 돌려서 맞는 부분을 체크한다. int slow = nums[0], fast = nums[0]; do{ slow = nums[slow]; fast = nums[nums[fast]]; }while(slow != fast); slow = nums[0]; while(slow != fast){ slow = nums[slow]; fast = nums[fast]; } return slow; } } 투 포인터를 활용한 싸이클 탐지(플로이드 알고리즘 - 토끼와 거북이)를 사용 해당 배열을 변경하지 않고, 추가공간을 사용하지 않도록 한다. 두 포인터를 각각 1, 2칸씩 이동하고 만나게 한다음 시작점을 재검색한다. * 출처 https://leetcode.com/problems/find-t

Naver Blog

JAVA_LeetCode 289_Game of Life

JAVA_LeetCode 289_Game of Life 풀이 class Solution { public void gameOfLife(int[][] board) { int n = board.length, m = board[0].length; // 8방향 탐색을 위한 배열 (시계 방향), dx는 행, dy는 열을 의미 int[] dx = {-1, -1, -1, 0, 1, 1, 1, 0}; int[] dy = {-1, 0, 1, 1, 1, 0, -1, -1}; // in-place 변경을 위해 상태 마킹 for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ int live = 0; // 살아 있는 이웃 개수 카운트 for(int k = 0; k < 8; k++){ // 8방향 모두 탐색 int ni = i + dx[k]; int nj = j + dy[k]; // 경계 처리: 격자 바깥은 무시 if(ni < 0 || ni >= n || nj <

Naver Blog

JAVA_LeetCode 299_Bulls and Cows

JAVA_LeetCode 299_Bulls and Cows 풀이 class Solution { public String getHint(String secret, String guess) { // 배열에 출연 빈도를 관리하고 아스키코드를 이용하여 정수로 변환한다. int bulls = 0, cows = 0; int[] nums = new int[10]; for(int i = 0; i < secret.length(); i++){ char s = secret.charAt(i), g = guess.charAt(i); if(s == g) bulls++; else{ // 이전, 이후의 출연 빈도 체크 if(nums[s - '0'] < 0) cows++; if(nums[g - '0'] > 0) cows++; // 이전, 이후에 출연 빈도 초기화 nums[s - '0']++; nums[g - '0']--; } } return bulls + "A" + cows + "B"; } } 출연 빈도 확인,

Naver Blog

JAVA_LeetCode 300_Longest Increasing Subsequence

JAVA_LeetCode 300_Longest Increasing Subsequence 풀이 class Solution { public int lengthOfLIS(int[] nums) { List<Integer> list = new ArrayList<>(); for(int num : nums){ int temp = Collections.binarySearch(list, num); // 이진 탐색 >> num이 들어갈 인덱스(값이 없으면 -1) if(temp < 0) temp = -(temp + 1); // -1 대비 if(temp == list.size()) list.add(num); // 증가하는 경우 끝에 넣기 else list.set(temp, num); // 크지 않은 경우 해당 인덱스에 대체 값 초기화하기 } return list.size(); } } 이진 탐색, 대체 삽입, 배열 순회 풀이 * 출처 https://leetcode.com/problems/longest-in

Naver Blog

JAVA_LeetCode 304_Range Sum Query 2D - Immutable

JAVA_LeetCode 304_Range Sum Query 2D - Immutable 풀이 class NumMatrix { private int[][] prefix; public NumMatrix(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; prefix = new int[m + 1][n + 1]; // 점차 우측 하단으로 가면서 해당 요소 값을 계산하면서 초기화해준다. for(int i = 1; i <= m; ++i){ for(int j = 1; j <= n; ++j){ prefix[i][j] = prefix[i - 1][j] + prefix[i][j - 1] - prefix[i - 1][j - 1] + matrix[i - 1][j - 1]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { // 0행 0열 기준으로 파라미터를 받아서

Naver Blog

JAVA_LeetCode 306_Additive Number

JAVA_LeetCode 306_Additive Number 풀이 class Solution { public boolean isAdditiveNumber(String num) { // 첫 숫자 길이 i, 두 번째 숫자 길이 j 범위 제한, 최대 절반까지만 고려 int len = num.length(); for(int i = 1; i <= len / 2; i++){ if(num.charAt(0) == '0' && i > 1) break; for(int j = 1; Math.max(i, j) <= len - i - j; j++){ if(num.charAt(i) == '0' && j > 1) break; if(isValid(num, i, j)) return true; } } return false; } // 백트래킹 함수, 인덱스와 두 숫자의 길이 정보로 탐색 private boolean isValid(String num, int i, int j) { String first = num.s

Naver Blog

JAVA_LeetCode 307_Range Sum Query - Mutable

JAVA_LeetCode 307_Range Sum Query - Mutable 풀이 class FenwickTree { private int[] sums; // Fenwick Tree 초기화 (크기 n) public FenwickTree(int n){ sums = new int[n + 1]; } // i번째 원소에 delta 값을 더함 (트리 업데이트) public void add(int i, int delta){ while(i < sums.length){ sums[i] += delta; // 현재 위치에 delta 더하기 i += i & -i; // 다음 인덱스로 이동 (BIT의 특성 이용) - 범위를 벗어나면 종료 } } // 1부터 i까지의 누적합 계산 public int get(int i){ int sum = 0; while(i > 0){ sum += sums[i]; i -= i & -i; } return sum; } } class NumArray { private int[]

Naver Blog

JAVA_LeetCode 264_Ugly Number II

JAVA_LeetCode 264_Ugly Number II 풀이 class Solution { public int nthUglyNumber(int n) { // 2, 3, 5를 체크하면서 배수와 일치 시 값 초기화한다. // 중복없이 작은 수부터 차례대로 2, 3, 5의 배수를 생성해나가는 구조 int[] ugly = new int[n]; ugly[0] = 1; int i2 = 0, i3 = 0, i5 = 0; int next2 = 2, next3 = 3, next5 = 5; for(int i = 1; i < n; i++){ int nextUgly = Math.min(next2, Math.min(next3, next5)); ugly[i] = nextUgly; if(nextUgly == next2) next2 = ugly[++i2] * 2; if(nextUgly == next3) next3 = ugly[++i3] * 3; if(nextUgly == next5) next5 = ugly[

Naver Blog

JAVA_LeetCode 274_H_Index

JAVA_LeetCode 274_H_Index 풀이 class Solution { public int hIndex(int[] citations) { // 오름차순 정렬해서 논문 인용 횟수와 현 수를 비교해서, h 이상 인용된 논문이 h편 이상인 경우를 찾는다. Arrays.sort(citations); int len = citations.length; for(int h = len; h > 0; h--) { if(citations[len - h] >= h) return h; } return 0; } } 배열 정렬, 현 수와 인덱스에 해당하는 값 체크 * 출처 https://leetcode.com/problems/h-index/?envType=problem-list-v2&envId=2fir0h51

Naver Blog

JAVA_LeetCode 275_H_Index II

JAVA_LeetCode 275_H_Index II 풀이 class Solution { public int hIndex(int[] citations) { int len = citations.length; int left = 0, right = len; // 이진 탐색으로 배열 전체를 순회하는 것을 피함 while(left < right){ int mid = left + (right - left) / 2; if(citations[len - mid - 1] >= mid + 1) left = mid + 1; else right = mid; } return left; } } 이진 탐색을 이용한 불필요한 반복 작업 제거 이전 문제와 달리 정렬된 배열을 기준으로 푸는 문제 * 출처 https://leetcode.com/problems/h-index-ii/?envType=problem-list-v2&envId=2fir0h51

Naver Blog

JAVA_LeetCode 279_Perfect Squares

JAVA_LeetCode 279_Perfect Squares 풀이 class Solution { public int numSquares(int n) { // dp[i]는 i를 완전제곱수의 합으로 만드는 최소 개수를 저장 int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; // 0은 0개의 제곱수로 표현 가능 // 점화식 : 현재 숫자 i에서 가능한 완전 제곱수(j⑵)를 빼고 남은 수의 최솟값에 1을 더하여 최소값을 구하는 방식 for(int i = 1; i <= n; i++){ for(int j = 1; j * j <= i; j++) dp[i] = Math.min(dp[i], dp[i - j * j] + 1); } return dp[n]; } } dp, 점화식 풀이 n을 완전 제곱수(예: 1, 4, 9, 16, ...)의 합으로 표현할 때, 최소 몇 개의 완전 제곱수가 필요한가에 대한 문제 dp[i]를

Naver Blog

JAVA_LeetCode 260_Single Number III

JAVA_LeetCode 260_Single Number III 풀이 class Solution { public int[] singleNumber(int[] nums) { // 모든 수를 XOR해서 두 개의 고유 숫자의 XOR 결과 얻기(xor을 통해 중복 수를 체크할 수 있음) int xor = 0, bit = 0; for(int num : nums) xor ^= num; // xor 결과에서 최하위 1비트 추출 (두 숫자가 다른 비트 위치) bit = xor & (-xor); // 최하위 1비트를 기준으로 nums를 두 그룹(0 또는 1)으로 나누어 각각 XOR 처리 int a = 0, b = 0; for(int num : nums){ if((num & bit) != 0) a ^= num; else b ^= num; } return new int[]{a, b}; } } 두개의 유니크 수 찾기, 비트 연산, 최하위 1비트 추출 이전 문제와 달리 두개의 유니크 수를 찾는 문제 * 출

Naver Blog

JAVA_LeetCode 155_Min Stack

JAVA_LeetCode 155_Min Stack 풀이 class MinStack { private Stack<Integer> stack; private Stack<Integer> minStack; public MinStack() { stack = new Stack<>(); minStack = new Stack<>(); // 최초값 비교를 위해 최댓값을 삽입 minStack.push(Integer.MAX_VALUE); } public void push(int val) { stack.push(val); // 현재 최소값과 새 값 중 더 작은 값을 minStack에 저장 minStack.push(Math.min(minStack.peek(), val)); } public void pop() { stack.pop(); // minStack도 같이 pop (항상 동기화) minStack.pop(); } public int top() { return stack.peek(); } public i

Naver Blog

JAVA_LeetCode 162_Find Peak Element

JAVA_LeetCode 162_Find Peak Element 풀이 class Solution { public int findPeakElement(int[] nums) { int left = 0, right = nums.length - 1, mid = 0; while(left < right){ mid = left + (right - left) / 2; if(nums[mid] < nums[mid + 1]) left = mid + 1; // 오른쪽에 peak가 있음 else right = mid; // 왼쪽에 peak가 있음(혹은 mid가 peak) } return left; // left == right가 되는 순간 peak } } * 출처 https://leetcode.com/problems/find-peak-element

Naver Blog

JAVA_LeetCode 164_Maximum Gap

JAVA_LeetCode 164_Maximum Gap 풀이 class Solution { public int maximumGap(int[] nums) { if(nums.length < 2) return 0; // 2개 미만이면 gap이 존재할 수 없음 // 전체 원소에서 최소, 최대값 찾기 int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; for(int num : nums){ min = Math.min(min, num); max = Math.max(max, num); } if(min == max) return 0; // 배열에 커버하는 범위(최대 - 최소 값에서 개수만큼 나눠진 몫) int gap = (int) Math.ceil((double)(max - min) / (nums.length - 1)), size = nums.length - 1; // 각 구간 내 두 연속된 요소의 최소, 최대값 저장 int[] arrMin = new in

Naver Blog

JAVA_LeetCode 165_Compare Version Numbers

JAVA_LeetCode 165_Compare Version Numbers 풀이 class Solution { public int compareVersion(String version1, String version2) { // '.'을 기준으로 숫자를 판별하여 각 수를 비교한다. int i = 0, j = 0, len1 = version1.length(), len2 = version2.length(), num1 = 0, num2 = 0; while(i < len1 || j < len2){ num1 = 0; num2 = 0; while(i < len1 && version1.charAt(i) != '.'){ // version1에서 숫자 부분 추출 num1 = num1 * 10 + (version1.charAt(i) - '0'); i++; } while(j < len2 && version2.charAt(j) != '.'){ // version2에서 숫자 부분 추출 num2 = num2

Naver Blog

JAVA_LeetCode 166_Fraction to Recurring Decimal

JAVA_LeetCode 166_Fraction to Recurring Decimal 풀이 class Solution { public String fractionToDecimal(int numerator, int denominator) { // 소수점 이하의 수의 반복 여부를 체크한다. if(numerator == 0) return "0"; StringBuilder sb = new StringBuilder(); // 부호 처리(음수 여부 확인) if((numerator < 0) ^ (denominator < 0)) sb.append("-"); long num = Math.abs((long)numerator), num2 = Math.abs((long)denominator); sb.append(num / num2); long r = num % num2; if(r == 0) return sb.toString(); sb.append("."); Map<Long, Integer> map = n

Naver Blog

JAVA_LeetCode 167_Two Sum II - Input Array Is Sorted

JAVA_LeetCode 167_Two Sum II - Input Array Is Sorted 풀이 class Solution { public int[] twoSum(int[] numbers, int target) { // 두 포인터의 합계와 target 값을 비교하여 위치를 조정한다. int left = 0, right = numbers.length - 1, sum = 0; while(left < right) { sum = numbers[left] + numbers[right]; // 배열의 index는 0부터 시작하므로 1을 더해줌 // 합이 작으면 왼쪽 포인터를 오른쪽으로 이동 // 합이 크면 오른쪽 포인터를 왼쪽으로 이동 if(sum == target) return new int[]{left + 1, right + 1}; else if(sum < target) left++; else right--; } // 문제 조건상 답이 항상 존재하므로 도달하지 않음 return new

Naver Blog

JAVA_LeetCode 172_Factorial Trailing Zeroes

JAVA_LeetCode 172_Factorial Trailing Zeroes 풀이 class Solution { public int trailingZeroes(int n) { // 10의 인수 2, 5에서 5를 체크하는 방식 // 5의 거듭제곱으로 나누어 몫을 더함 int cnt = 0; for(long i = 5; i <= n; i *= 5) cnt += n / i; return cnt; } } 숫자 끝부분에 연속적으로 나오는 0의 개수를 출력하는 문제 팩토리얼을 계산하지 않고 문제를 해결하는 방식이 존재 뒤의 '0'이 붙으려면 10이 존재하고, 10의 인수 2, 5에서 찾기 2는 많으므로(거듭제곱도 고려해야함) 5의 배수를 확인하는 방식 * 출처 https://leetcode.com/problems/factorial-trailing-zeroes

Naver Blog

JAVA_LeetCode 173_Binary Search Tree Iterator

JAVA_LeetCode 173_Binary Search Tree Iterator 풀이 class BSTIterator { private Stack<TreeNode> stack = new Stack<>(); // 생성자: 루트에서 왼쪽 끝까지 스택에 쌓음 public BSTIterator(TreeNode root) { pushLeft(root); } // 다음(오름차순) 값을 반환 public int next() { TreeNode node = stack.pop(); // 현재 노드의 오른쪽 자식을 다시 스택에 추가함 pushLeft(node.right); return node.val; } // 더 남은 노드가 있으면 true public boolean hasNext() { return !stack.isEmpty(); } // 주어진 노드에서 가장 왼쪽까지 모두 스택에 추가 private void pushLeft(TreeNode node){ while (node != null){ s

Naver Blog

JAVA_LeetCode 179_Largest Number

JAVA_LeetCode 179_Largest Number 풀이 class Solution { public String largestNumber(int[] nums) { // 숫자들을 문자열로 변환 String[] strNums = new String[nums.length]; for(int i = 0; i < nums.length; i++) strNums[i] = String.valueOf(nums[i]); // 내림차순 정렬 Arrays.sort(strNums, (a, b) -> (b + a).compareTo(a + b)); // 첫번째 요소 중 0이 있는 경우 "0" 반환 if(strNums[0].equals("0")) return "0"; // 문자열 조합 StringBuilder sb = new StringBuilder(); for(String str : strNums) sb.append(str); return sb.toString(); } } 배열 정렬을 이용하여 첫 요소

Naver Blog

JAVA_LeetCode 187_Repeated DNA Sequences

JAVA_LeetCode 187_Repeated DNA Sequences 풀이 class Solution { public List<String> findRepeatedDnaSequences(String s) { int len = s.length(); List<String> res = new ArrayList<>(); if(len <= 10) return res; Set<String> set = new HashSet<>(); // 이미 본 10글자 문자열 저장 Set<String> repeated = new HashSet<>(); // 반복된 10글자 문자열 저장 for(int i = 0; i <= len - 10; i++){ String str = s.substring(i, i + 10); // 이미 본 문자열이면 반복 문자열 집합에 추가 if(!set.add(str)) repeated.add(str); } res.addAll(repeated); return res; } } set

Naver Blog

JAVA_LeetCode 189_Rotate Array

JAVA_LeetCode 189_Rotate Array 풀이 class Solution { public void rotate(int[] nums, int k) { // k기준 분할된 역순들을 다시 역순으로 바꾸면서 요소 위치를 변경한다. int len = nums.length; k %= len; // k가 n보다 클 때 대비 reverse(nums, 0, len - 1); reverse(nums, 0, k - 1); reverse(nums, k, len - 1); } // 역순으로 적용 private void reverse(int[] nums, int start, int end){ while(start < end){ int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } } 특정 값 기준으로 나눠서 서로 역순으로 바꾸기 변경된 양쪽 순서를 다시 역순으로 바꿈으로써 통일된 순서를 갖춤

Naver Blog

JAVA_LeetCode 198_House Robber

JAVA_LeetCode 198_House Robber 풀이 class Solution { public int rob(int[] nums) { // 현재 위치, 인접 위치 중 가장 큰 값을 찾아 점차 더해간다. if(nums == null || nums.length == 0) return 0; int len = nums.length; if(len == 1) return nums[0]; int[] dp = new int[len]; dp[0] = nums[0]; dp[1] = Math.max(nums[0], nums[1]); for (int i = 2; i < len; i++) { // 현재 집 i를 털 경우 (i - 2까지 최대값 + 현재 집 금액)와 // 집 i를 털지 않고 i - 1까지의 최대값 중 좋은 값 선택 dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); } return dp[len - 1]; } } dp를 이용, 현재 위치 기준 인접

Naver Blog

JAVA_LeetCode 199_Binary Tree Right Side View

JAVA_LeetCode 199_Binary Tree Right Side View 풀이 class Solution { public List<Integer> rightSideView(TreeNode root) { // dfs를 이용하여 각 깊이별 우측값을 선별한다. List<Integer> list = new ArrayList<>(); dfs(root, 0, list); return list; } // 깊이우선탐색(DFS)으로 오른쪽부터 탐색 private void dfs(TreeNode node, int depth, List<Integer> list){ if(node == null) return; // 현재 깊이의 첫 번째 노드를 오른쪽 노드부터 우선하여 저장 if(depth == list.size()) list.add(node.val); // 오른쪽 자식 먼저 탐색하여 오른쪽 끝 노드가 먼저 저장되도록 함 dfs(node.right, depth + 1, list); // 그 다음

Naver Blog

JAVA_LeetCode 200_Number of Islands

JAVA_LeetCode 200_Number of Islands 풀이 class Solution { public int numIslands(char[][] grid) { // 중첩 for문으로 grid를 순회, 1을 발견할 경우 체크한다음 해당 영역을 0으로 변경 if(grid == null || grid.length == 0) return 0; int row = grid.length, col = grid[0].length, cnt = 0; for(int i = 0; i < row; i++){ for(int j = 0; j < col; j++){ if(grid[i][j] == '1'){ cnt++; dfs(grid, i, j); } } } return cnt; } // 영역 발견 시 값을 0으로 변경하며 인접한 영역을 체크함 private void dfs(char[][] grid, int i, int j){ // 1이 아니거나 해당 영역을 벗어났을 경우 return if(i < 0

Naver Blog

JAVA_LeetCode 133_Clone Graph

JAVA_LeetCode 133_Clone Graph 풀이 class Solution { // 기존 노드를 복사하여 새로운 노드로 만들기 위해 따로 선언 private Map<Node, Node> visited = new HashMap<>(); public Node cloneGraph(Node node) { if(node == null) return null; // 이미 복사된 노드인 경우 바로 반환 if(visited.containsKey(node)) return visited.get(node); // 현재 노드 복사해서 map에 key/value로 담기 Node clone = new Node(node.val); visited.put(node, clone); // 이웃들을 재귀적으로 복사하여 연결 for(Node neighbor : node.neighbors) clone.neighbors.add(cloneGraph(neighbor)); return clone; } } 방문 노드를

Naver Blog

JAVA_LeetCode 134_Gas Station

JAVA_LeetCode 134_Gas Station 풀이 class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { // 한바퀴 돌 수 있는 지점을 찾기 int totalGas = 0, totalCost = 0, tank = 0, start = 0; // 누적 연료가 음수가 되는 순간, 그 구간에서 출발해 봐야 도달 못함. for (int i = 0; i < gas.length; i++) { totalGas += gas[i]; totalCost += cost[i]; tank += gas[i] - cost[i]; // 다음 인덱스(i + 1)부터 다시 도전. if(tank < 0){ start = i + 1; tank = 0; } } // 전체 얻는 연료 < 전체 필요한 연료라면 불가능 if(totalGas < totalCost) return -1; return start; } } 선형 탐색 풀이, 한바퀴 돌 때

Naver Blog

JAVA_LeetCode 137_Single Number II

JAVA_LeetCode 137_Single Number II 풀이 class Solution { public int singleNumber(int[] nums) { // 비트 비교와 누적 횟수를 통한 풀이법 // 세번 등장하면 ones와 twos에서 모두 제거 int ones = 0, twos = 0; for(int num : nums){ ones = (ones ^ num) & ~twos; // 한번 등장한 비트 twos = (twos ^ num) & ~ones; // 두번 등장한 비트 } return ones; } } 요소 검색 시 비트 확인을 통해 특정 변수에 담기 생각보다 어려운 문제 * 출처 https://leetcode.com/problems/single-number-ii

Naver Blog

JAVA_LeetCode 138_Copy List with Random Pointer

JAVA_LeetCode 138_Copy List with Random Pointer 풀이 class Solution { public Node copyRandomList(Node head) { // map 키를 원본 노드, value를 복제 노드로 넣는다. if(head == null) return null; HashMap<Node, Node> map = new HashMap<>(); // 모든 노드 복제 및 해시맵에 저장 Node curr = head; while(curr != null){ map.put(curr, new Node(curr.val)); curr = curr.next; } // 각 복제 노드의 next와 random 연결 설정 curr = head; while(curr != null){ Node copyNode = map.get(curr); copyNode.next = (curr.next != null) ? map.get(curr.next) : null; copyNo

Naver Blog

JAVA_LeetCode 139_Word Break

JAVA_LeetCode 139_Word Break 풀이 class Solution { public boolean wordBreak(String s, List<String> wordDict) { // Set을 이용하여 해당 문자열이 존재하는지 체크하기 Set<String> wordSet = new HashSet<>(wordDict); boolean[] dp = new boolean[s.length() + 1]; // 빈 문자열은 항상 분할하기 위해 첫번째 요소를 true로 설정 dp[0] = true; for(int i = 1; i <= s.length(); i++){ for(int j = 0; j < i; j++){ if(dp[j] && wordSet.contains(s.substring(j, i))){ dp[i] = true; break; } } } return dp[s.length()]; } } set, dp를 이용하여 for문의 정보를 재사용하는 방식 문자열 체크를 통해 존재

Naver Blog

JAVA_LeetCode 142_Linked List Cycle II

JAVA_LeetCode 142_Linked List Cycle II 풀이 public class Solution { public ListNode detectCycle(ListNode head) { if(head == null) return null; // 사이클을 돌기 위해 O(1)의 조건에 맞도록 포인터를 사용 ListNode slow = head; ListNode fast = head; // 포인터 비교를 위해 각각 1, 2칸 이동으로 적용 while(fast != null && fast.next != null){ slow = slow.next; // 느린 포인터는 1칸 이동 fast = fast.next.next; // 빠른 포인터는 2칸 이동 if(slow == fast){ // 두 포인터가 만나면 사이클 존재하니까 시작 노드 찾기 slow = head; // 느린 포인터를 head로 이동(손바뀜) // 두 포인터 모두 한 칸씩 이동 while(slow != fast){ s

Naver Blog

JAVA_LeetCode 143_Reorder List

JAVA_LeetCode 143_Reorder List 풀이 class Solution { public void reorderList(ListNode head) { if(head == null || head.next == null) return; // 중간 노드를 찾아서 해당 중간 노드 기준 이후의 노드를 역순으로 따로 만들고, 기존 순서와 역순의 노드들을 서로 번갈아 병합한다. ListNode current = head; ListNode prev = null; int len = 0; while(current != null){ len++; current = current.next; } // 중간 노드까지 이동 current = head; for(int i = 0; i < (len / 2); i++){ prev = current; current = current.next; } prev.next = null; // 중간에서 끊기 // 역순과 같이 번갈아 병합한다. ListNode rev

Naver Blog

JAVA_LeetCode 146_LRU Cache

JAVA_LeetCode 146_LRU Cache 풀이 class LRUCache { private final int capacity; private final HashMap<Integer, Node> cache; private final Node head, tail; // 이중 연결 리스트 노드 정의 private static class Node{ int key, value; Node prev, next; Node(int key, int value){ this.key = key; this.value = value; } } public LRUCache(int capacity) { this.capacity = capacity; cache = new HashMap<>(capacity); head = new Node(0, 0); // 더미 헤드 tail = new Node(0, 0); // 더미 꼬리 head.next = tail; tail.prev = head; } public int

Naver Blog

JAVA_LeetCode 147_Insertion Sort List

JAVA_LeetCode 147_Insertion Sort List 풀이 class Solution { public ListNode insertionSortList(ListNode head) { if(head == null || head.next == null) return head; // 정렬된 리스트를 따로 만들어서 값을 비교하며 삽입해간다. ListNode dummy = new ListNode(0); dummy.next = head; ListNode prev = head; // 이전 노드 ListNode curr = head.next; // 삽입할 노드 while(curr != null){ if(prev.val <= curr.val){ // 이미 정렬된 상태이므로 prev, curr를 한 칸씩 이동 prev = curr; curr = curr.next; }else{ // curr 노드를 정렬된 리스트에서 알맞은 위치에 삽입 ListNode temp = dummy; while(t

Naver Blog

JAVA_LeetCode 148_Sort List

JAVA_LeetCode 148_Sort List 풀이 class Solution { public ListNode sortList(ListNode head) { if(head == null || head.next == null) return head; // 중간 노드 찾기 ListNode mid = getMid(head); // 왼쪽 리스트, 오른쪽 리스트로 재귀 호출하여 각각 정렬 ListNode left = sortList(head); ListNode right = sortList(mid); // 병합 정렬 return merge(left, right); } private ListNode getMid(ListNode head) { ListNode slow = head, fast = head, prev = null; // fast & slow로 중간 위치 찾기 while(fast != null && fast.next != null){ prev = slow; // slow 직전 노드

Naver Blog

JAVA_LeetCode 150_Evaluate Reverse Polish Notation

JAVA_LeetCode 150_Evaluate Reverse Polish Notation 풀이 class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<>(); for(String token : tokens){ if(token.equals("+")) stack.push(stack.pop() + stack.pop()); else if(token.equals("*")) stack.push(stack.pop() * stack.pop()); else if(token.equals("-")){ int temp = stack.pop(); stack.push(stack.pop() - temp); }else if(token.equals("/")){ int temp = stack.pop(); stack.push(stack.pop() / temp); }else stack.push(Integer.pars

Naver Blog

JAVA_LeetCode 151_Reverse Words in a String

JAVA_LeetCode 151_Reverse Words in a String 풀이 class Solution { public String reverseWords(String s) { // 문자열을 가변적인 문자 배열로 변환 char[] chars = s.trim().toCharArray(); int len = chars.length, start = 0, end = 0; // 전체 문자열을 뒤집기 reverse(chars, 0, len - 1); // 각 단어를 다시 뒤집기 while(start < len){ // 공백 아닌 문자 찾기 end = start; while(end < len && chars[end] != ' ') end++; reverse(chars, start, end - 1); start = end + 1; } // 단어 사이 공백 하나로 정리 return cleanSpaces(chars, len); } // 부분 문자열 뒤집기 private void reverse(

Naver Blog

JAVA_LeetCode 152_Maximum Product Subarray

JAVA_LeetCode 152_Maximum Product Subarray 풀이 class Solution { public int maxProduct(int[] nums) { // 부분 배열 중 곱한 값중 최대값 찾기 int max = nums[0], min = nums[0], res = nums[0]; for(int i = 1; i < nums.length; i++) { int num = nums[i]; int tempMax = Math.max(Math.max(num, max * num), min * num); int tempMin = Math.min(Math.min(num, max * num), min * num); max = tempMax; min = tempMin; res = Math.max(res, max); } return res; } } dp, 연속된 부분 배열 중 곱한 값중 가장 큰 값 찾기 순회하면서 음수 간 곱한 것들도 체크 필요 * 출처 https://leetc

Naver Blog

JAVA_LeetCode 153_Find Minimum in Rotated Sorted Array

JAVA_LeetCode 153_Find Minimum in Rotated Sorted Array 풀이 class Solution { public int findMin(int[] nums) { // 이진 탐색으로 범위를 줄여서 찾기 int left = 0, right = nums.length - 1, mid = 0; while(left < right){ mid = left + (right - left) / 2; if(nums[mid] > nums[right]) left = mid + 1; // 중간 값이 오른쪽 끝 값보다 크면, 최솟값은 mid 오른쪽에 있음 else right = mid; // 중간 값이 오른쪽 끝 값보다 작거나 같으면, 최솟값은 mid 또는 mid 왼쪽에 있음 } return nums[left]; } } 정렬 배열중 회전 위치를 찾는 문제 이진 탐색으로 체크하기 배열 요소 중 좌측으로부터 확인할때 현재 요소 우측값이 좌측값보다 작거나 같은 경우 지금까지의 요소 중

Naver Blog

JAVA_LeetCode 109_Convert Sorted List to Binary Search Tree

JAVA_LeetCode 109_Convert Sorted List to Binary Search Tree 풀이 class Solution { // head 전역변수 private ListNode head; public TreeNode sortedListToBST(ListNode head) { // 중위 순회 기반 재귀 방식을 통한 풀이 this.head = head; int size = getSize(head); return buildTree(size); } // 연결 리스트 길이를 재는 함수 private int getSize(ListNode node) { int cnt = 0; while(node != null) { cnt++; node = node.next; } return cnt; } // 중위 순회 기반 재귀 함수 private TreeNode buildTree(int size) { if(size <= 0) return null; TreeNode left = buildTr

Naver Blog

JAVA_LeetCode 113_Path Sum II

JAVA_LeetCode 113_Path Sum II 풀이 class Solution { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { // dfs 방식을 통해 모든 방식을 전부 고려하여 탐색한다. List<List<Integer>> list = new ArrayList<>(); dfs(root, 0, targetSum, new ArrayList<>(), list); return list; } private void dfs(TreeNode node, int currSum, int targetSum, List<Integer> temp, List<List<Integer>> list){ if(node == null) return; temp.add(node.val); currSum += node.val; // 리프 노드 & 경로 합이 targetSum일 때 결과 추가 if(node.left == null && node

Naver Blog

JAVA_LeetCode 114_Flatten Binary Tree to Linked List

JAVA_LeetCode 114_Flatten Binary Tree to Linked List 풀이 class Solution { public void flatten(TreeNode root) { // BST 문제가 아니라, 단순히 전위 순회에 대한 문제 TreeNode cur = root; while(cur != null){ if(cur.left != null){ // 현재 노드의 왼쪽 서브트리에서 가장 오른쪽 노드 찾기 TreeNode rightmost = cur.left; while(rightmost.right != null) rightmost = rightmost.right; // 오른쪽 서브트리를 연결 rightmost.right = cur.right; // 왼쪽을 오른쪽으로 옮기고, 왼쪽은 null로 설정 cur.right = cur.left; cur.left = null; } // 다음 노드로 이동 (오른쪽 방향) cur = cur.right; } } } 트리 구조 노드

Naver Blog

JAVA_LeetCode 116_Populating Next Right Pointers in Each Node

JAVA_LeetCode 116_Populating Next Right Pointers in Each Node 풀이 class Solution { public Node connect(Node root) { if (root == null) return null; connectNodes(root.left, root.right); return root; } private void connectNodes(Node left, Node right){ // 노드별 맨 끝자리는 결국 null이 들어감('#'는 시각적 표시로 인해 보여지는 것) if(left == null || right == null) return; // 같은 부모 내의 왼쪽 자식과 오른쪽 자식을 연결 left.next = right; // 왼쪽 자식의 오른쪽과 오른쪽 자식의 왼쪽을 연결 (부모가 다른 경우) connectNodes(left.right, right.left); // 재귀로 각 자식 내부 연결 connectNodes

Naver Blog

JAVA_프로그래머스_그림 확대

JAVA_프로그래머스_그림 확대 풀이 class Solution { public String[] solution(String[] picture, int k) { int height = picture.length; int width = picture[0].length(); String[] answer = new String[height * k]; // stringbuilder를 통해 문자열을 만들고 저장 String[] rows = new String[height]; for(int i = 0; i < height; i++){ StringBuilder sb = new StringBuilder(width * k); for(int j = 0; j < width; j++){ char ch = picture[i].charAt(j); for(int temp = 0; temp < k; temp++) sb.append(ch); } rows[i] = sb.toString(); } // answer 데

Naver Blog

JAVA_LeetCode 117_Populating Next Right Pointers in Each Node II

JAVA_LeetCode 117_Populating Next Right Pointers in Each Node II 풀이 class Solution { public Node connect(Node root) { if(root == null) return null; Node current = root; // 현재 레벨의 시작 노드 while(current != null){ Node dummyHead = new Node(0); // 다음 레벨을 연결할 더미 노드 Node tail = dummyHead; // 다음 레벨 연결을 위한 포인터 // 현재 레벨 모든 노드 순회하며 다음 레벨 연결 // tail로 새로 연결할 노드로 옮겨서 연결을 이어붙여나감 while(current != null){ if(current.left != null){ tail.next = current.left; tail = tail.next; } if (current.right != null) { tail.next

Naver Blog

JAVA_LeetCode 120_Triangle

JAVA_LeetCode 120_Triangle 풀이 class Solution { public int minimumTotal(List<List<Integer>> triangle) { // dp를 이용, 맨 아래부터 가장 작은값을 체크한다. // 마지막 행의 값을 복사해서 start int len = triangle.size(); int[] dp = new int[len]; for(int i = 0; i < len; i++) dp[i] = triangle.get(len - 1).get(i); // 아래에서 위로 올라가며 최소값 갱신 // n - 1이 마지막 요소이므로 그 위의 n - 2 부터 시작한다. // 행 번호에 맞춰 요소가 존재하므로 현재값(col)과 그 아래 값(col, col + 1)을 더해 값 초기화한다. // 점차 맨 위로 옮겨가며 총계(가장 작은 값)를 찾아낸다. for(int row = len - 2; row >= 0; row--){ for(int col = 0;

Naver Blog

JAVA_LeetCode 122_Best Time to Buy and Sell Stock II

JAVA_LeetCode 122_Best Time to Buy and Sell Stock II 풀이 class Solution { public int maxProfit(int[] prices) { // 인접한 수의 차감된 수가 0보다 큰경우 반환값에 계속 더해준다. int profit = 0; for(int i = 0; i < prices.length - 1; i++) profit += Math.max(0, prices[i + 1] - prices[i]); return profit; } } 인접한 수와 차감된 수를 찾아서 해당 값을 더해나간다. * 출처 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii

Naver Blog

JAVA_LeetCode 128_Longest Consecutive Sequence

JAVA_LeetCode 128_Longest Consecutive Sequence 풀이 class Solution { public int longestConsecutive(int[] nums) { // O(n) 풀이를 위해 정렬 없이 사용 Set<Integer> set = new HashSet<>(); for(int num : nums) set.add(num); int len = 0, temp = 0, chk = 0; for(int num : set) { // 바로 앞 숫자가 없을 때만 시작점을 실행 if (!set.contains(num - 1)) { temp = num; chk = 1; // 다음 숫자가 있으면 계속 증가 while(set.contains(temp + 1)){ temp += 1; chk += 1; } len = Math.max(len, chk); } } return len; } } hashset, O(n) 풀이, 정렬(O(n log n)) 방식 없이 풀이 set

Naver Blog

JAVA_LeetCode 129_Sum Root to Leaf Numbers

JAVA_LeetCode 129_Sum Root to Leaf Numbers 풀이 class Solution { public int sumNumbers(TreeNode root) { return dfs(root, 0); } private int dfs(TreeNode node, int current) { // 바텀업 방식 if(node == null) return 0; // 현재 노드까지의 숫자 current = current * 10 + node.val; // 리프 노드면 해당 숫자 반환 -> 지금까지 더해진 값들을 반환 if(node.left == null && node.right == null) return current; // 왼쪽 결과 + 오른쪽 결과 합산 return dfs(node.left, current) + dfs(node.right, current); } } 트리, 이진트리, 깊이 우선 탐색(dfs) 방식 풀이 노드 값이 한자리인것을 이용한 바텀업 방식 풀이 리프

Naver Blog

JAVA_LeetCode 130_Surrounded Regions

JAVA_LeetCode 130_Surrounded Regions 풀이 class Solution { public void solve(char[][] board) { if(board == null || board.length == 0) return; int row = board.length, col = board[0].length; Queue<int[]> queue = new LinkedList<>(); // 테두리에서 'O' 발견 시 'T' 단어로 치환(감싸고 있는 부분 제외) for(int i = 0; i < row; i++) { if(board[i][0] == 'O'){ queue.offer(new int[]{i, 0}); board[i][0] = 'T'; } if(board[i][col - 1] == 'O'){ queue.offer(new int[]{i, col - 1}); board[i][col - 1] = 'T';} } for(int j = 0; j < col; j++){

Naver Blog

JAVA_LeetCode 131_Palindrome Partitioning

JAVA_LeetCode 131_Palindrome Partitioning 풀이 class Solution { public List<List<String>> partition(String s) { int len = s.length(), end = 0; boolean[][] isPalindrome = new boolean[len][len]; // 회문 여부를 DP로 사전 계산 for(int i = 1; i <= len; i++){ for(int j = 0; j <= len - i; j++) { end = j + i - 1; if(s.charAt(j) == s.charAt(end)){ if(i <= 2) isPalindrome[j][end] = true; // 길이가 1 또는 2면 안쪽 검사 필요 없음 else isPalindrome[j][end] = isPalindrome[j + 1][end - 1]; // 안쪽 문자열이 회문이면 긴 문자열도 회문 } } } List<List<Stri

Naver Blog

JAVA_프로그래머스_겹치는 선분의 길이

JAVA_프로그래머스_겹치는 선분의 길이 풀이 class Solution { public int solution(int[][] lines) { int[] nums = new int[201]; int overlap = 0, cnt = 0, st = 0, end = 0; // 각 선분 입력 처리 for(int[] line : lines){ st = line[0] + 100; end = line[1] + 100; // 시작점 +1, 끝점 -1 (끝은 포함하지 않는 반열림 구간) nums[st]++; nums[end]--; } for(int i = 0; i < 200; i++){ // 200까지여야 1칸씩 계산됨 cnt += nums[i]; if(cnt >= 2) overlap++; // 두 개 이상 겹침 } return overlap; } } 특정 구간 값 체크, 시작 / 끝 값은 제외 해당 구간의 값이 2이상인 경우 체크 * 출처 https://school.programmers.co.k

Naver Blog

JAVA_LeetCode 96_Unique Binary Search Trees

JAVA_LeetCode 96_Unique Binary Search Trees 풀이 class Solution { public int numTrees(int n) { int[] dp = new int[n + 1]; dp[0] = 1; // 0개 노드로 만들 수 있는 트리는 1개 (null) dp[1] = 1; // 점화식 계산을 위해 dp[1]에 1로 초기화한다. // dp[i]는 총 i개의 노드로 만들 수 있는 BST 개수 for(int i = 2; i <= n; i++){ for(int j = 1; j <= i; j++){ // j를 루트로 선택 - 왼쪽 서브트리: j - 1개, 오른쪽 서브트리: i - j개 dp[i] += dp[j - 1] * dp[i - j]; } } return dp[n]; } } 이진검색트리, 이진검색트리 dp 적용, 점화식 계산(각 항 사이의 관계식) * 출처 https://leetcode.com/problems/unique-binary-search-t

Naver Blog

JAVA_LeetCode 97_Interleaving String

JAVA_LeetCode 97_Interleaving String 풀이 class Solution { public boolean isInterleave(String s1, String s2, String s3) { // s1와 s2의 단어의 순서가 정확히 섞여야함 int len = s1.length(), len2 = s2.length(), len3 = s3.length(), tmp = 0; if(len + len2 != len3) return false; boolean[] dp = new boolean[len2 + 1]; dp[0] = true; // 아무것도 없는경우를 고려하여 0부터 시작한다. for(int i = 0; i <= len; ++i){ for(int j = 0; j <= len2; ++j){ // 둘다 0일때 지나감(증감문 조건과 상관없이 0도 시작됨) if(i == 0 && j == 0) continue; // s3의 인덱스를 사용하기 위해 i, j 파라미터를 넣어

Naver Blog

JAVA_LeetCode 98_Validate Binary Search Tree

JAVA_LeetCode 98_Validate Binary Search Tree 풀이 class Solution { public boolean isValidBST(TreeNode root) { return isVaild(root, null, null); } private boolean isVaild(TreeNode node, Integer low, Integer high) { // BST 조건 맞추기 if(node == null) return true; // 왼쪽 서브트리 구할 때 현재 노드가 상한값, 오른쪽 서브트리 구할 때 현재 노드가 하한값으로 세팅한다. if((low != null && node.val <= low) || (high != null && node.val >= high)) return false; return isVaild(node.left, low, node.val) && isVaild(node.right, node.val, high); } } * 출처 http

Naver Blog

JAVA_LeetCode 99_Recover Binary Search Tree

JAVA_LeetCode 99_Recover Binary Search Tree 풀이 class Solution { // 노드의 잘못된 값을 저장하기 위한 클래스 private static class Bst{ TreeNode first = null; // 첫번째 문제 노드 TreeNode middle = null; // 첫번째 문제 노드 옆의 바로 다음 노드(작은 값) TreeNode last = null; // 두번째 문제 노드 TreeNode prev = null; // 순회 이전 방문 노드 } public void recoverTree(TreeNode root) { // BST에서 두 노드를 바꿔서 BST 조건에 맞추기 위해, 바꿀 두 노드를 체크해서 class 변수에 초기화한다. Bst bst = new Bst(); inVaild(root, bst); int tmp = 0; // 교환하기 if (bst.first != null && bst.last != null) { tmp =

Naver Blog

JAVA_LeetCode 102_Binary Tree Level Order Traversal

JAVA_LeetCode 102_Binary Tree Level Order Traversal 풀이 class Solution { public List<List<Integer>> levelOrder(TreeNode root) { // 이진트리의 레벨 순서대로 반환하는 문제 List<List<Integer>> list = new ArrayList<>(); if(root == null) return list; // queue를 효율적으로 사용하기 위해 ArrayList가 아닌 LinkedList로 선언 Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); // 기본값 세팅 int len = 0; while(!queue.isEmpty()){ len = queue.size(); // 현재 레벨 크기 측정 List<Integer> level = new ArrayList<>(); for(int i = 0; i < len; i++){ // 0

Naver Blog

JAVA_LeetCode 103_Binary Tree Zigzag Level Order Traversal

JAVA_LeetCode 103_Binary Tree Zigzag Level Order Traversal 풀이 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<List<Integer>> zigzagLevelOrder(TreeNode root) { // queue와 방향에 맞춰 리스트를 노드로 넣어준다. List<List<Integer>> list = new Arra

Naver Blog

JAVA_LeetCode 105_Construct Binary Tree from Preorder and Inorder Traversal

JAVA_LeetCode 105_Construct Binary Tree from Preorder and Inorder Traversal 풀이 class Solution { private Map<Integer, Integer> inorderIndexMap; private int preorderIndex; // preorder 배열에서 다음 트리의 루트가 될 위치 public TreeNode buildTree(int[] preorder, int[] inorder) { inorderIndexMap = new HashMap<>(); for(int i = 0; i < inorder.length; i++) inorderIndexMap.put(inorder[i], i); // inorder 값 초기화 preorderIndex = 0; // 재귀 실행 return buildSubtree(preorder, 0, inorder.length - 1); } private TreeNode buildSubt

Naver Blog

JAVA_LeetCode 106_Construct Binary Tree from Inorder and Postorder Traversal

JAVA_LeetCode 106_Construct Binary Tree from Inorder and Postorder Traversal 풀이 class Solution { private Map<Integer, Integer> inorderIndexMap; private int postorderIndex; // postorder 배열에서 다음 트리의 루트가 될 위치 public TreeNode buildTree(int[] inorder, int[] postorder) { inorderIndexMap = new HashMap<>(); for(int i = 0; i < inorder.length; i++) inorderIndexMap.put(inorder[i], i); // inorder 값 초기화 postorderIndex = postorder.length - 1; // 트리 루트(마지막 인덱스) return buildSubtree(postorder, 0, inorder.length

Naver Blog

JAVA_LeetCode 107_Binary Tree Level Order Traversal II

JAVA_LeetCode 107_Binary Tree Level Order Traversal II 풀이 class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { // 아래에서 위로 올라감 List<List<Integer>> list = new LinkedList<>(); if(root == null) return list; // queue를 효율적으로 사용하기 위해 ArrayList가 아닌 LinkedList로 선언 Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int len = 0; while(!queue.isEmpty()) { len = queue.size(); // 현재 레벨 크기 측정 List<Integer> levelNodes = new ArrayList<>(); for(int i = 0; i < len; i++){ TreeNode

Naver Blog

JAVA_LeetCode 86_Partition List

JAVA_LeetCode 86_Partition List 풀이 class Solution { public ListNode partition(ListNode head, int x) { // 특정값 기준으로 나눠 노드에 차례대로 붙인 다음 마지막에 두 노드를 붙여준다. ListNode dummy1 = new ListNode(0); // 앞쪽 더미노드 ListNode dummy2 = new ListNode(0); // 뒤쪽 더미노드 ListNode node1 = dummy1; // 앞쪽 노드 ListNode node2 = dummy2; // 뒤쪽 노드 while(head != null){ if(head.val < x){ // 앞쪽 노드 node1.next = head; node1 = node1.next; }else{ // 뒤쪽 노드 node2.next = head; node2 = node2.next; } head = head.next; } node2.next = null; // 뒤쪽 노드

Naver Blog

JAVA_LeetCode 89_Gray Code

JAVA_LeetCode 89_Gray Code 풀이 class Solution { public List<Integer> grayCode(int n) { // list에 총 원소 개수(2^n)만큼 반복해서 그레이코드 공식에 맞춰 넣는다. List<Integer> list = new ArrayList<>(); for(int i = 0; i < (1 << n); i++) list.add(i ^ (i >> 1)); return list; } } 원소 개수에 맞춘 그레이코드, 그레이코드 공식 구하기 * 출처 https://leetcode.com/problems/gray-code

1 2 3 4 5 6 7 8 9 10