joonbread의 등록된 링크

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

Naver Blog

JAVA_LeetCode 90_Subsets II

JAVA_LeetCode 90_Subsets II 풀이 class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(nums); // 중복 처리 용이하게 정렬 back(0, nums, new ArrayList<>(), list); return list; } private void back(int st, int[] nums, List<Integer> temp, List<List<Integer>> list) { // 시작 시 바로 리스트에 담기 list.add(new ArrayList<>(temp)); for(int i = st; i < nums.length; i++) { // 같은 depth에서 이전 값과 같으면 건너뜀(중복 제거) if(i > st && nums[i] == nums[i - 1]) continue;

Naver Blog

JAVA_LeetCode 91_Decode Ways

JAVA_LeetCode 91_Decode Ways 풀이 class Solution { public int numDecodings(String s) { // 없으면 바로 0 반환 if(s == null || s.length() == 0) return 0; int len = s.length(), num = 0; // dp를 이용하기 위해 길이 + 1로 배열 선언 int[] dp = new int[len + 1]; dp[0] = 1; // 빈문자열 체크(한글자 용도) dp[1] = s.charAt(0) != '0' ? 1 : 0; // 첫 글자 // 2글자를 체크하기 위해 2부터 시작 for(int i = 2; i <= len; i++){ if(s.charAt(i - 1) != '0') dp[i] += dp[i - 1]; // 한 글자(0이 아닌경우 체크) num = Integer.parseInt(s.substring(i - 2, i)); // 두 글자 if(num >= 10 && nu

Naver Blog

JAVA_LeetCode 92_Reverse Linked List II

JAVA_LeetCode 92_Reverse Linked List II 풀이 class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { // 더미 리스트 노드 생성 ListNode dummy = new ListNode(0); dummy.next = head; // 구간 뒤집기 전 노드로 설정 ListNode node = dummy; for(int i = 1; i < left; i++) node = node.next; // 전환할 첫번째 노드(left 위치) ListNode curr = node.next; // 노드 전환 for(int i = 0; i < right - left; i++){ ListNode temp = curr.next; // left 다음 노드 curr.next = temp.next; // left 다음 노드에 temp의 다음 노드를 연결(dummy에서 temp가 분리됨)

Naver Blog

JAVA_LeetCode 93_Restore IP Addresses

JAVA_LeetCode 93_Restore IP Addresses 풀이 class Solution { public List<String> restoreIpAddresses(String s) { // 백트래킹으로 ip분석하기(최소 길이는 4, 최대는 12) List<String> list = new ArrayList<>(); if(s == null || s.length() < 4 || s.length() > 12) return list; back(0, s, new ArrayList<>(), list); return list; } private void back(int start, String s, List<String> str, List<String> list) { String part; // 4개의 파트를 만들었고, 문자열 끝까지 썼으면 유효 if(str.size() == 4) { if(start == s.length()) list.add(String.join(".", str));

Naver Blog

JAVA_LeetCode 95_Unique Binary Search Trees II

JAVA_LeetCode 95_Unique Binary Search Trees II 풀이 class Solution { public List<TreeNode> generateTrees(int n) { if(n == 0) return new ArrayList<>(); return tree(1, n); } private List<TreeNode> tree(int start, int end) { List<TreeNode> allTrees = new ArrayList<>(); // 시작값이 끝값보다 큰 경우 범위가 잘못되어 빈 트리를 추가한다. if(start > end){ allTrees.add(null); return allTrees; } // start부터 end까지 루트 노드로 선택해서 트리 구성 for(int i = start; i <= end; i++){ // 이진탐색트리 조건에 의해 아래 내용 실행 // 루트 i를 기준으로 가능한 왼쪽 서브트리 모두 구하기 List<TreeNo

Naver Blog

JAVA_LeetCode 75_Sort Colors

JAVA_LeetCode 75_Sort Colors 풀이 class Solution { public void sortColors(int[] nums) { int temp = 0; // 버블 정렬 구조로 푼 문제 for(int i = 0; i < nums.length - 1; i++){ for(int j = 0; j < nums.length - 1 - i; j++){ if(nums[j] > nums[j + 1]){ temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; } } } } } 버블 정렬(단일 원패스 구조 정렬) * 출처 https://leetcode.com/problems/sort-colors

Naver Blog

JAVA_LeetCode 77_Combinations

JAVA_LeetCode 77_Combinations 풀이 class Solution { public List<List<Integer>> combine(int n, int k) { // 1부터 n까지의 범위중, k개의 숫자로 조합을 출력하기 // [1, 2]와 [2, 1]이 같다고 한 것을 보아, 요소 위치를 바꿔도 중복값으로 체크됨 // 이미 이전에 나온 값은 순서가 바꿔져도 횟수로 세지 않음 // 백트래킹을 이용하여 횟수를 체크함 List<List<Integer>> list = new ArrayList<>(); back(1, n, list, new Stack<>(), k); return list; } public void back(int st, int n, List<List<Integer>> list, Stack<Integer> stack, int k){ // 스택 사이즈 비교 if(stack.size() == k){ list.add(new ArrayList<>(stack));

Naver Blog

JAVA_LeetCode 78_Subsets

JAVA_LeetCode 78_Subsets 풀이 class Solution { public List<List<Integer>> subsets(int[] nums) { // 순서가 상관없는 배열을 넣기 위해 백트래킹형식으로 실행 List<List<Integer>> list = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); back(0, nums, list, list2); return list; } public void back(int st, int[] nums, List<List<Integer>> list, List<Integer> list2){ // 실행 시 리스트에 담아주기 list.add(new ArrayList<>(list2)); for(int i = st; i < nums.length; i++){ list2.add(nums[i]); back(i + 1, nums, list, list2); list2.remove(l

Naver Blog

JAVA_LeetCode 79_Word Search

JAVA_LeetCode 79_Word Search 풀이 class Solution { public boolean exist(char[][] board, String word) { // dfs, 백트래킹 사용 int rows = board.length, cols = board[0].length; char[] arr = word.toCharArray(); for(int i = 0; i < rows; i++) { for(int j = 0; j < cols; j++) { if(dfs(board, arr, 0, i, j)) return true; } } return false; } public boolean dfs(char[][] board, char[] word, int idx, int row, int col) { // 경계 벗어나거나 단어가 불일치한경우 if(row < 0 || col < 0 || row >= board.length || col >= board[0].length || b

Naver Blog

JAVA_LeetCode 80_Remove Duplicates from Sorted Array II

JAVA_LeetCode 80_Remove Duplicates from Sorted Array II 풀이 class Solution { public int removeDuplicates(int[] nums) { // 슬라이딩 윈도우, 중복 단어 최소 2개 적용 int cnt = 0; for(int i = 0; i < nums.length; i++){ if(cnt < 2 || nums[cnt - 2] != nums[i]) nums[cnt++] = nums[i]; } return cnt; } } 슬라이딩 윈도우, 순차적 단어 체크, 중복 단어 최소 2개 적용 * 출처 https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii

Naver Blog

JAVA_LeetCode 81_Search in Rotated Sorted Array II

JAVA_LeetCode 81_Search in Rotated Sorted Array II 풀이 class Solution { public boolean search(int[] nums, int target) { int left = 0, right = nums.length - 1; while(left <= right){ int mid = left + (right - left) / 2; if(nums[mid] == target) return true; // 중복 처리: 삼중 값이 같을 때 진척이 없으므로 양쪽을 한 칸씩 좁힘 if(nums[left] == nums[mid] && nums[mid] == nums[right]){ left++; right--; continue; } if(nums[left] <= nums[mid]) { // 왼쪽 구간이 정렬되어 있을 때 // target이 왼쪽 정렬 구간 내에 있다면 왼쪽으로 서치 범위 좁힘 if(nums[left] <= target &&

Naver Blog

JAVA_LeetCode 82_Remove Duplicates from Sorted List II

JAVA_LeetCode 82_Remove Duplicates from Sorted List II 풀이 class Solution { public ListNode deleteDuplicates(ListNode head) { // 더미 노드와 head 노드를 따로 초기화해준다음, 조건에 부합할때마다 노드를 변경해준다. ListNode node = new ListNode(0); // 더미 노드 생성 node.next = head; ListNode prev = node; // 중복 없는 마지막 노드 ListNode curr = head; boolean bool; while(curr != null){ bool = false; while(curr.next != null && curr.val == curr.next.val){ // 현재 중복되는 구간 curr = curr.next; bool = true; } if(bool){ // 중복구간 다음으로 건너뛰도록 변경 prev.next = curr

Naver Blog

JAVA_LeetCode 54_Spiral Matrix

JAVA_LeetCode 54_Spiral Matrix 풀이 class Solution { public List<Integer> spiralOrder(int[][] matrix) { // 시작, 끝 위치들을 변수로 설정하여 해당 지점에 도달할때마다 방향을 바꿔준다. ArrayList<Integer> list = new ArrayList<>(); int left = 0, right = matrix[0].length - 1, top = 0, down = matrix.length - 1; while(left <= right && top <= down){ for(int i = left; i <= right; i++) list.add(matrix[top][i]); top++; for(int i = top; i <= down; i++) list.add(matrix[i][right]); right--; if(top <= down){ for(int i = right; i >= left; i--)

Naver Blog

JAVA_LeetCode 55_Jump Game

JAVA_LeetCode 55_Jump Game 풀이 class Solution { public boolean canJump(int[] nums) { // 인덱스 + 요소값과 이전 인덱스에서 점프한 값중 최대 값을 찾는다. int res = 0; for(int i = 0; i < nums.length; i++){ // 마지막 인덱스에 도달하지 못할 경우 false를 반환 if(i > res) return false; res = Math.max(res, i + nums[i]); } return true; } } 배열, 인덱스별 값 점프, 최대값과 인덱스 비교 * 출처 https://leetcode.com/problems/jump-game

Naver Blog

JAVA_LeetCode 56_Merge Intervals

JAVA_LeetCode 56_Merge Intervals 풀이 class Solution { public int[][] merge(int[][] intervals) { int len = intervals.length, idx = 0; // 정렬 Arrays.sort(intervals, Comparator.comparing(v -> v[0])); // 정렬된 이전 요소와 현 요소를 비교, 조건에 부합한 경우 최대값을 설정해주고, 아닌 경우 다음 인덱스를 검색한다. for(int i = 1; i < len; i++) { if(intervals[i][0] <= intervals[idx][1]){ intervals[idx][1] = Math.max(intervals[i][1], intervals[idx][1]); }else{ idx++; intervals[idx] = intervals[i]; } } // 정렬 범위의 배열 반환 return Arrays.copyOfRange(interval

Naver Blog

JAVA_LeetCode 57_Insert Interval

JAVA_LeetCode 57_Insert Interval 풀이 class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { // list에 병합 전, 병합, 병합 후 구간을 담아준다. ArrayList<int[]> list = new ArrayList<int[]>(); int len = intervals.length, i = 0; // 병합 전 범위 while(i < len && intervals[i][1] < newInterval[0]) list.add(intervals[i++]); // 병합 범위 while(i < len && intervals[i][0] <= newInterval[1]){ newInterval[0] = Math.min(intervals[i][0], newInterval[0]); newInterval[1] = Math.max(intervals[i++][1], newInterval[1

Naver Blog

JAVA_LeetCode 59_Spiral Matrix II

JAVA_LeetCode 59_Spiral Matrix II 풀이 class Solution { public int[][] generateMatrix(int n) { // 2차원 배열에 맞는 조건에 값을 초기화하고 삽입한다음, 위치를 계속해서 바꿔간다. int[][] arr = new int[n][n]; int left = 0, right = n-1, top = 0, down = n-1, num = 1; while(num <= n * n){ for(int i = left; i <= right; i++) arr[top][i] = num++; top++; for(int i = top; i <= down; i++) arr[i][right] = num++; right--; for(int i = right; i >= left; i--) arr[down][i] = num++; down--; for(int i = down; i >= top; i--) arr[i][left] = num++; lef

Naver Blog

JAVA_LeetCode 61_Rotate List

JAVA_LeetCode 61_Rotate List 풀이 class Solution { public ListNode rotateRight(ListNode head, int k) { if(head == null || head.next == null || k == 0) return head; ListNode node = head, node2 = head; int cnt = 1; // 리스트 순회하면서 노드 체크 while(node.next != null){ node = node.next; cnt++; } // 꼬리 체크하기 k %= cnt; // 만약 0인경우 head 그대로 반환 if(k == 0) return head; // 연결 node.next = head; // 새 꼬리 위치를 찾기 위해 반복 for(int i = 0; i < cnt - k - 1; i++) node2 = node2.next; ListNode node3 = node2.next; node2.next = null;

Naver Blog

JAVA_LeetCode 62_Unique Paths

JAVA_LeetCode 62_Unique Paths 풀이 class Solution { public int uniquePaths(int m, int n) { int[][] dp = new int[m + 1][n + 1]; // 도착지점을 1로 지정 dp[m - 1][n - 1] = 1; // 역순으로 이동하면서 이동 경로 총 개수를 계속해서 더해준다. for(int i = m - 1; i >= 0; i--){ for(int j = n - 1; j >= 0; j--){ dp[i][j] = (i == m - 1 && j == n - 1) ? 1 : (dp[i + 1][j] + dp[i][j + 1]); } } // 시작 지점을 반환한다. return dp[0][0]; } } 행렬, 위치별 이동, 동적프로그래밍 * 출처 https://leetcode.com/problems/unique-paths

Naver Blog

JAVA_LeetCode 63_Unique Paths II

JAVA_LeetCode 63_Unique Paths II 풀이 class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { // 기존 배열에서 장애물이 없는 지역을 1로 초기화한다음 이후 반복문을 통해 값을 더해나간다. int row = obstacleGrid.length, col = obstacleGrid[0].length; if(obstacleGrid[0][0] == 1) return 0; if(row == 1 && col == 1) return 1; int[][] dp = new int[row][col]; // 1인경우를 찾아서 체크 for(int i = 1; i < row; i++) { if(obstacleGrid[i][0] == 1) break; dp[i][0] = 1; } // 1인경우를 찾아서 체크 for(int i = 1; i < col; i++) { if(obstacleGrid[0][i]

Naver Blog

JAVA_LeetCode 64_Minimum Path Sum

JAVA_LeetCode 64_Minimum Path Sum 풀이 class Solution { public int minPathSum(int[][] grid) { // 동적프로그래밍을 이용해 푼 문제 int row = grid.length, col = grid[0].length; int[][] dp = new int[row][col]; dp[0][0] = grid[0][0]; // 1행 세팅 for(int i = 1; i < col; i++) dp[0][i] = dp[0][i - 1] + grid[0][i]; // 1열 세팅 for(int i = 1; i < row; i++) dp[i][0] = dp[i - 1][0] + grid[i][0]; // (1,1)부터 값 세팅할 때 가장 작은 값을 더해나감 for(int i = 1; i < row; i++){ for(int j = 1; j < col; j++) dp[i][j] = grid[i][j] + Math.min(dp[i - 1][

Naver Blog

JAVA_LeetCode 71_Simplify Path

JAVA_LeetCode 71_Simplify Path 풀이 class Solution { public String simplifyPath(String path) { // 스택을 이용한 풀이법 Stack<String> stack = new Stack<>(); String[] arr = path.split("/"); for(String str : arr){ if(str.equals(".") || str.isEmpty()) continue; // . 또는 비어있을경우 무시 else if(str.equals("..")){ // 상위 디렉토리인경우 if(!stack.isEmpty()) stack.pop(); // 있을 때 빼기 }else stack.push(str); // 나머지인경우 추가 } return "/" + String.join("/", stack); // 루트와 스택 합치기 } } 스택, 실제 사용되는 디렉토리 경로 표시로 추정 * 출처 https://leetcode.com/pr

Naver Blog

JAVA_LeetCode 72_Edit Distance

JAVA_LeetCode 72_Edit Distance 풀이 class Solution { public int minDistance(String word1, String word2) { // 레벤슈타인 거리 알고리즘을 이용한 풀이법 int row = word1.length(), col = word2.length(); int dp[][] = new int[row + 1][col + 1]; // 먼저 2차원 배열에 첫번째 행, 첫번째 열에 해당 순번에 맞춰 값을 세팅한다. for(int i = 0; i <= row; i++) dp[i][0] = i; for(int i = 0; i <= col; i++) dp[0][i] = i; // 레벤슈타인 거리 알고리즘에 의해 word1와 word2의 char 요소가 같은지 확인한다. for(int i = 1; i <= row; i++){ for(int j = 1; j <= col; j++){ // 같은 경우 왼쪽 대각선의 값을 그대로 갖고온다. /

Naver Blog

JAVA_LeetCode 73_Set Matrix Zeroes

JAVA_LeetCode 73_Set Matrix Zeroes 풀이 class Solution { public void setZeroes(int[][] matrix) { int row = matrix[0].length, col = matrix.length; boolean rowBool = false, colBool = false; // 첫번째 행 체크 for(int i = 0; i < row; i++){ if(matrix[0][i] == 0) rowBool = true; } // 첫번째 열 체크 for(int i = 0; i < col; i++){ if(matrix[i][0] == 0) colBool = true; } // 0인경우 첫번째 행, 열 값을 0으로 초기화 for(int i = 1; i < col; i++){ for(int j = 1; j < row; j++){ if(matrix[i][j] == 0){ matrix[i][0] = 0; matrix[0][j] = 0; } }

Naver Blog

JAVA_LeetCode 74_Search a 2D Matrix

JAVA_LeetCode 74_Search a 2D Matrix 풀이 class Solution { public boolean searchMatrix(int[][] matrix, int target) { // target이 matrix 요소와 일치한 경우 true, 아닌 경우 값 비교에 따라 위치 인덱스를 바꿔준다. int len = matrix.length, num = 0, num2 = matrix[0].length - 1; while(num < len && num2 >= 0){ if(target == matrix[num][num2]) return true; else if(target < matrix[num][num2]) num2--; else num++; } return false; } } 배열 중 일치여부 찾기 * 출처 https://leetcode.com/problems/search-a-2d-matrix

Naver Blog

JAVA_LeetCode 45_Jump Game II

JAVA_LeetCode 45_Jump Game II 풀이 class Solution { public int jump(int[] nums) { if(nums.length <= 1) return 0; // 횟수 / 점프 범위 끝 / 최대 점프 범위 값을 구한다. int cnt = 0, idx = 0, temp = 0; // 현재 위치에서 최대 점프 범위값을 계속 초기화 // 최대 점프 범위가 점프 범위의 끝과 같을 때 초기화해주면서 횟수를 추가한다. for(int i = 0; i < nums.length - 1; i++){ temp = Math.max(temp, i + nums[i]); if(i == idx){ idx = temp; cnt++; } } return cnt; } } 배열, 현재 위치에서 점프 범위 끝과 최대 점프 범위를 비교하여 풀기 * 출처 https://leetcode.com/problems/jump-game-ii

Naver Blog

JAVA_LeetCode 46_Permutations

JAVA_LeetCode 46_Permutations 풀이 class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> list = new ArrayList<>(); check(nums, list, new ArrayList<>()); return list; } public void check(int[] nums, List<List<Integer>> list, List<Integer> temp){ // 모두 돌면 리스트에 담기 if(temp.size() == nums.length){ list.add(new ArrayList<>(temp)); return; } // 배열별 반복하되, 존재하면 넘기고 미존재시 추가 후 백트래킹 for(int num : nums){ if(temp.contains(num)) continue; temp.add(num); check(nums, list, temp); te

Naver Blog

JAVA_LeetCode 47_Permutations II

JAVA_LeetCode 47_Permutations II 풀이 class Solution { public List<List<Integer>> permuteUnique(int[] nums) { Arrays.sort(nums); List<List<Integer>> list = new ArrayList<>(); // 사용 여부를 파악하기 위해 논리 배열을 선언해준다. boolean[] bool = new boolean[nums.length]; check(list, new ArrayList<>(), nums, bool); return list; } public void check(List<List<Integer>> list, List<Integer> temp, int[] nums, boolean[] bool){ if(nums.length == temp.size()) { list.add(new ArrayList<>(temp)); return; } for(int i = 0; i < nums.

Naver Blog

JAVA_LeetCode 48_Rotate Image

JAVA_LeetCode 48_Rotate Image 풀이 class Solution { public void rotate(int[][] matrix) { int len = matrix.length, len2 = matrix[0].length, temp = 0; /** 1 2 3 4 5 6 7 8 9 */ // 행 / 열을 바꿔준다. for (int i = 0; i < len; i++) { for (int j = i; j < len2; j++) { // 동일하지 않은경우 변경 if (i != j) { temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } } /** 1 4 7 2 5 8 3 6 9 */ // 행의 좌우 반전 for (int i = 0; i < len; i++) { for (int j = 0; j < len2 / 2 ; j++) { temp = matrix[i][j]; matrix[i][j]

Naver Blog

JAVA_LeetCode 49_Group Anagrams

JAVA_LeetCode 49_Group Anagrams 풀이 class Solution { public List<List<String>> groupAnagrams(String[] strs) { // 애너그림 특징 상, 같은 알파벳으로 여러 단어를 작성할 수 있도록 하는 내용 // hashmap을 이용하여 key-value형식으로 키별 애너그램 값을 구분한다. Map<String, List<String>> map = new HashMap<>(); String temp, sort; // 문자열을 문자배열로 만들어서 정렬 후 map의 키로 비교하여 존재하는지 확인한다. for(String str: strs){ temp = str; char[] ch = temp.toCharArray(); Arrays.sort(ch); sort = new String(ch); if(!map.containsKey(sort)) map.put(sort, new ArrayList<>()); map.get(sort

Naver Blog

JAVA_LeetCode 50_Pow(x, n)

JAVA_LeetCode 50_Pow(x, n) 풀이 class Solution { public double myPow(double x, int n) { // math의 pow를 쓰지않고 지수 법칙을 따라 푸는 문제 if(n < 0){ x = 1 / x; // n이 Integer.MIN_VALUE일때 절대값 오류가 있어서 +1을 해줘야 한다. return x * myPow(x, -(n + 1)); } if(n == 0) return 1.0; if(n % 2 == 0) return myPow(x * x, n / 2); return (x * myPow(x, n - 1)); } } Math의 pow를 쓰지 않고 풀기, 지수 법칙 문제에서 절대값 오류를 확인할 수 있었다. * 출처 https://leetcode.com/problems/powx-n

Naver Blog

JAVA_LeetCode 53_Maximum Subarray

JAVA_LeetCode 53_Maximum Subarray 풀이 class Solution { public int maxSubArray(int[] nums) { // 카데인 알고리즘을 통해 풀 수 있다. // 순차적으로 더한값과 현재 값을 비교하면서 합계를 변경한다. int max = nums[0], temp = nums[0]; for(int i = 1; i < nums.length; i++){ temp = Math.max(nums[i], temp + nums[i]); max = Math.max(max, temp); } return max; } } 카데인 알고리즘 * 출처 https://leetcode.com/problems/maximum-subarray

Naver Blog

JAVA_LeetCode 38_Count and Say

JAVA_LeetCode 38_Count and Say 풀이 class Solution { public String countAndSay(int n) { // 1이면 1반환 if(n == 1) return "1"; // n - 1을 파라미터로 넣어서 string으로 초기화 String str = countAndSay(n - 1); StringBuilder sb = new StringBuilder(); int num = 0, len = str.length(), i = 0; char ch; // 받은 파라미터만큼 실행 while(num < len){ // 문자 초기화 ch = str.charAt(num); i = num + 1; // 조건에 부합하면 개수 증가(같은 문자 연속 체크) while(i < len && str.charAt(i) == ch) i++; // 개수 더하고, 해당 숫자 더해주기 sb.append(i - num); sb.append(ch); // 초기화 num = i;

Naver Blog

JAVA_LeetCode 39_Combination Sum

JAVA_LeetCode 39_Combination Sum 풀이 class Solution { public static void check(int[] arr, int idx, int end, List<List<Integer>> list, List<Integer> temp){ // 인덱스가 배열 길이와 같고 다 맞은 경우(0인 경우) temp 리스트 담기 if(idx == arr.length){ if(end == 0){ list.add(new ArrayList<>(temp)); } return; } // 현재 값이 end보다 작거나 같은경우 해당 값을 넣고, 파라미터로 다시 넣어서 부른다. if(arr[idx] <= end){ temp.add(arr[idx]); // 요소 추가 check(arr, idx, end - arr[idx], list, temp); // 같은 수, idx 중복 사용 가능 temp.remove(temp.size() - 1); // 마지막 추가 요소를 빼야 이전

Naver Blog

JAVA_LeetCode 40_Combination Sum II

JAVA_LeetCode 40_Combination Sum II 풀이 class Solution { public void check(int[] arr, int idx, int end, List<List<Integer>> list, List<Integer> temp){ // 0인경우 temp 리스트 담기 if(end == 0){ list.add(new ArrayList<>(temp)); return; } // idx기준으로 반복 for(int i = idx; i < arr.length; i++){ if(i > idx && arr[i] == arr[i - 1]) continue; // 다른 인덱스, 같은 값 중복 체크 if(arr[i] > end) break; // 현 요소가 end보다 큰 경우 끝내기 temp.add(arr[i]); // 요소 추가 check(arr, i + 1, end - arr[i], list, temp); // 중복 idx 방지 및 end값 감소 temp.remo

Naver Blog

JAVA_LeetCode 43_Multiply Strings

JAVA_LeetCode 43_Multiply Strings 풀이 class Solution { public String multiply(String num1, String num2) { // 두수를 곱하는데, 두수를 bigInteger와 정수로 변환하지 않도록 함 if(num1.equals("0") || num2.equals("0")) return "0"; int[] res = new int[num1.length() + num2.length()]; int mul = 0, sum = 0; StringBuilder sb = new StringBuilder(); for(int i = num1.length() - 1; i >= 0; i--){ for(int j = num2.length() - 1; j >= 0; j--){ mul = (num2.charAt(j) - '0') * (num1.charAt(i) - '0'); // 각 자리 값을 곱해준다. sum = res[i + j + 1] +

Naver Blog

JAVA_LeetCode 8_String to Integer_atoi

JAVA_LeetCode 8_String to Integer_atoi 풀이 class Solution { public int myAtoi(String s) { if(s.equals("")) return 0; long num = 0; int len = s.length(), i = 0, sign = 1; // 공백 무시 while(i < len && s.charAt(i) == ' ') i++; // 부호 설정 if(i < len && (s.charAt(i) == '+' || s.charAt(i) == '-')) sign = (s.charAt(i++) == '-') ? -1 : 1; // 숫자 체크 while(i < len && s.charAt(i) >= '0' && s.charAt(i) <= '9'){ num *= 10; num += (s.charAt(i) - '0'); if(sign * num > Integer.MAX_VALUE) return Integer.MAX_VALUE; if(s

Naver Blog

JAVA_LeetCode 11_Container With Most Water

JAVA_LeetCode 11_Container With Most Water 풀이 class Solution { public int maxArea(int[] height) { // 양사이드 값을 기준으로 설정하여, 현재 구한 최대값과 현재 구할 수 있는 직사각형의 크기를 비교한다. int y1 = 0, y2 = height.length - 1, min = 0, max = 0; // 양쪽값이 같아지면 끝나며, 기둥 크기에 따라 양사이드 값을 조절한다. while(y1 < y2){ min = Math.min(height[y1], height[y2]) * (y2 - y1); max = Math.max(min, max); if(height[y1] == height[y2]){ y1++; y2--; }else{ if(height[y1] < height[y2]) y1++; else y2--; } } return max; } } * 출처 https://leetcode.com/problems/con

Naver Blog

JAVA_LeetCode 12_Integer to Roman

JAVA_LeetCode 12_Integer to Roman 풀이 class Solution { public String intToRoman(int num) { // 로마자별 숫자를 설정 int[] val = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] str = {"M", "CM", "D", "CD", "C", "XC", "L","XL", "X", "IX", "V", "IV", "I"}; StringBuilder sb = new StringBuilder(); // 순차적으로 큰수로 나눴을 때 몫이 0보다 클때까지 반복한다. for(int i = 0; i < val.length; i++){ if(num / val[i] > 0){ // 몫만큼 문자열로 더해준다. for(int j = 0; j < num / val[i]; j++) sb.append(str[i]); // 나머지 초기화 num %= val[i]; } }

Naver Blog

JAVA_LeetCode 15_3Sum

JAVA_LeetCode 15_3Sum 풀이 class Solution { public List<List<Integer>> threeSum(int[] nums) { int j = 0, k = 0, tot = 0; List<List<Integer>> list = new ArrayList<>(); Arrays.sort(nums); for(int i = 0; i < nums.length; i++){ // 중복값 건너뛰기 if(i > 0 && nums[i] == nums[i-1]) continue; // 앞 뒤 인덱스 설정 j = i + 1; k = nums.length - 1; while(j < k){ tot = nums[i] + nums[j] + nums[k]; // 합계가 클 경우 뒷부분을 앞으로, 작은 경우 앞부분을 뒤로, 0인경우 리스트에 담아준다. if(tot > 0) k--; else if(tot < 0) j++; else{ list.add(Arrays.asList(nums[i

Naver Blog

JAVA_LeetCode 16_3Sum Closest

JAVA_LeetCode 16_3Sum Closest 풀이 class Solution { public int threeSumClosest(int[] nums, int target) { // 정렬후 기준 인덱스로 요소 3개의 합이 target에 가까운 경우를 체크한다. Arrays.sort(nums); int len = nums.length, temp = nums[0] + nums[1] + nums[2], sum = 0, left = 0, right = 0; for(int i = 0; i < len - 2; i++){ left = i + 1; right = len - 1; while(left < right) { sum = nums[i] + nums[left] + nums[right]; if(Math.abs(temp - target) > Math.abs(sum - target)) temp = sum; if(sum < target) left++; else if(sum > target) r

Naver Blog

JAVA_LeetCode 17_Letter Combinations of a Phone Number

JAVA_LeetCode 17_Letter Combinations of a Phone Number 풀이 class Solution { // hashmap에 번호별 문자열을 정하기 private static final Map<Character, String> map = new HashMap<>(Map.of( '1', "", '2', "abc", '3', "def", '4', "ghi", '5', "jkl", '6', "mno", '7', "pqrs", '8', "tuv", '9', "wxyz" )); public List<String> letterCombinations(String digits) { if(digits == null || digits.length() == 0) return new ArrayList<>(); List<String> list = new ArrayList<String>(); // 재귀로 다음 문자를 시도한다. check(digits, 0, new StringB

Naver Blog

JAVA_LeetCode 18_4Sum

JAVA_LeetCode 18_4Sum 풀이 class Solution { public List<List<Integer>> fourSum(int[] nums, int target) { Arrays.sort(nums); List<List<Integer>> list = new ArrayList<>(); int len = nums.length, left = 0, right = 0; long sum = 0; for(int i = 0; i < len - 3; i++){ // 중복인경우 건너뛴다. if( i > 0 && nums[i] == nums[i -1]) continue; for(int j = i + 1 ; j < len - 2; j++){ // 중복인경우 건너뛴다. if(j > i + 1 && nums[j] == nums[j -1]) continue; left = j + 1; right = len - 1; // 목표와 합계가 같은지 확인한다. while(left < right){ sum

Naver Blog

JAVA_LeetCode 3498_Reverse Degree of a String

JAVA_LeetCode 3498_Reverse Degree of a String 풀이 class Solution { public int reverseDegree(String s) { // int로 형변환한 값을 123에서 뺀다음, 인덱스를 곱하여 반환값에 추가해준다. int sum = 0, idx = 1; for(char ch : s.toCharArray()){ sum += (123 - (int)ch) * idx; idx++; } return sum; } } * 출처 https://leetcode.com/problems/reverse-degree-of-a-string

Naver Blog

JAVA_LeetCode 3502_Minimum Cost to Reach Every Position

JAVA_LeetCode 3502_Minimum Cost to Reach Every Position 풀이 class Solution { public int[] minCosts(int[] cost) { // 작은 수를 뒤로 정렬 for(int i = 1; i < cost.length; i++){ cost[i] = Math.min(cost[i], cost[i - 1]); } return cost; } } * 출처 https://leetcode.com/problems/minimum-cost-to-reach-every-position

Naver Blog

JAVA_LeetCode 3507_Minimum Pair Removal to Sort Array I

JAVA_LeetCode 3507_Minimum Pair Removal to Sort Array I 풀이 class Solution { // 인접 쌍 값 체크 public boolean listCheck(List<Integer> arr) { for(int i = 0; i < arr.size() - 1; i++){ if(arr.get(i) > arr.get(i + 1)) return false; } return true; } public int minimumPairRemoval(int[] nums) { List<Integer> list = new ArrayList<>(); int cnt = 0, min = 0, idx = 0, sum = 0; for(int num : nums) list.add(num); while(!listCheck(list)) { min = Integer.MAX_VALUE; idx = -1; // 합이 최소가 되는 인접 쌍을 찾아 리스트에 넣어주기 위해 값을 찾는다

Naver Blog

JAVA_LeetCode 3512_Minimum Operations to Make Array Sum Divisible by K

JAVA_LeetCode 3512_Minimum Operations to Make Array Sum Divisible by K 풀이 class Solution { public int minOperations(int[] nums, int k) { // 요소를 모두 더한값이 k로 나눌때 나머지를 반환한다. int sum = 0; for(int num : nums) sum += num; return sum % k; } } * 출처 https://leetcode.com/problems/minimum-operations-to-make-array-sum-divisible-by-k

Naver Blog

JAVA_LeetCode 3516_Find Closest Person

JAVA_LeetCode 3516_Find Closest Person 풀이 class Solution { public int findClosest(int x, int y, int z) { // z를 기준으로 절대값에 따라 값을 반환한다. int p1 = Math.abs(z - x); int p2 = Math.abs(z - y); return p1 == p2 ? 0 : p1 > p2 ? 2 : 1; } } * 출처 https://leetcode.com/problems/find-closest-person

Naver Blog

JAVA_LeetCode 3536_Maximum Product of Two Digits

JAVA_LeetCode 3536_Maximum Product of Two Digits 풀이 class Solution { public int maxProduct(int n) { // 리스트에 각 수를 담고 정렬한다음, 가장 맨뒤와 그 전 값을 곱해준다. ArrayList<Integer> list = new ArrayList<>(); int len = 0; while(n != 0){ list.add(n % 10); n /= 10; } Collections.sort(list); len = list.size(); return list.get(len - 1) * list.get(len - 2); } } * 출처 https://leetcode.com/problems/maximum-product-of-two-digits

Naver Blog

JAVA_LeetCode 3541_Find Most Frequent Vowel and Consonant

JAVA_LeetCode 3541_Find Most Frequent Vowel and Consonant 풀이 class Solution { public int maxFreqSum(String s) { // 각 모음, 자음별 hashmap 변수에 키별 값을 저장한다음 최대값을 찾는다. HashMap<Character, Integer> map = new HashMap<>(), map2 = new HashMap<>(); int max = 0, max2 = 0; for(char ch : s.toCharArray()) { if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') map.put(ch, map.getOrDefault(ch, 0) + 1); else map2.put(ch, map2.getOrDefault(ch, 0) + 1); } for(int num : map.values()) max = Math.max(max, num

Naver Blog

JAVA_LeetCode 3545_Minimum Deletions for At Most K Distinct Characters

JAVA_LeetCode 3545_Minimum Deletions for At Most K Distinct Characters 풀이 class Solution { public int minDeletion(String s, int k) { // 26개의 배열에 s의 문자를 담은다음, 정렬하여 오름차순중 26- k 인덱스 이하의 나머지값들을 더해준다. int[] arr = new int[26]; int res = 0; for(char ch : s.toCharArray()) arr[ch - 'a']++; Arrays.sort(arr); for(int i = 0; i < 26 - k; i++) res += arr[i]; return res; } } * 출처 https://leetcode.com/problems/minimum-deletions-for-at-most-k-distinct-characters

Naver Blog

JAVA_LeetCode 3550_Smallest Index With Digit Sum Equal to Index

JAVA_LeetCode 3550_Smallest Index With Digit Sum Equal to Index 풀이 class Solution { public int smallestIndex(int[] nums) { // 반복해서 각 요소별에서 합과 인덱스가 같은 지 판별하고 같은 경우 인덱스를 반환한다. int sum = 0, num = 0; for(int i = 0; i < nums.length; i++){ sum = 0; num = nums[i]; while(num > 0){ sum += num % 10; num /= 10; } if(sum == i) return i; } return -1; } } * 출처 https://leetcode.com/problems/smallest-index-with-digit-sum-equal-to-index

Naver Blog

JAVA_LeetCode 2_Add Two Numbers

JAVA_LeetCode 2_Add Two Numbers 풀이 class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { // listnode의 포인터를 이용한 풀이법이다. ListNode dummy = new ListNode(); ListNode temp = dummy; int carry = 0, val = 0, val2 = 0, sum = 0; // 각 노드별 값을 더해서 올림값이 존재할 경우 체크하고, 나머지는 따로 저장한다. while(l1 != null || l2 != null || carry != 0){ val = (l1 != null) ? l1.val : 0; val2 = (l2 != null) ? l2.val : 0; sum = val + val2 + carry; carry = sum / 10; temp.next = new ListNode(sum % 10); temp = temp.next; if

Naver Blog

JAVA_LeetCode 3_Longest Substring Without Repeating Characters

JAVA_LeetCode 3_Longest Substring Without Repeating Characters 풀이 class Solution { public int lengthOfLongestSubstring(String s) { // 배열에 해당 문자별 개수를 체크하고, 중복값을 체크해서 최대값을 산출한다. int[] arr = new int[128]; int cnt = 0, num = 0, temp = 0; for(int i = 0; i < s.length(); i++) { temp = s.charAt(i); while(arr[temp] > 0) { arr[s.charAt(num)]--; num++; } arr[temp]++; cnt = Math.max(cnt, i - num + 1); } return cnt; } } * 출처 https://leetcode.com/problems/longest-substring-without-repeating-characters

Naver Blog

JAVA_LeetCode 5_Longest Palindromic Substring

JAVA_LeetCode 5_Longest Palindromic Substring 풀이 class Solution { int st, end; public String longestPalindrome(String s) { if(s.length() < 2) return s; // 가운데를 기점으로 양쪽값이 같은지 체크 for(int i = 0; i < s.length() - 1; i++){ check(s, i, i); // 홀수인경우 check(s, i, i + 1); // 짝수인경우 } return s.substring(st, st + end); } public void check(String str, int left, int right){ // 양쪽 문자가 일치할경우 양값 재 설정 while(left >= 0 && right < str.length() && str.charAt(left) == str.charAt(right)){ left--; right++; } // 마지막 지점 설정

Naver Blog

JAVA_LeetCode 6_Zigzag Conversion

JAVA_LeetCode 6_Zigzag Conversion 풀이 class Solution { public String convert(String s, int numRows) { // stringbuilder를 배열로 생성해서 각 char마다 인덱스에 따라 넣어준다. if(numRows <= 1 || numRows >= s.length()) return s; int idx = 0, num = 1; StringBuilder[] sb = new StringBuilder[numRows]; for(int i = 0; i < numRows; i++) sb[i] = new StringBuilder(); for(char ch : s.toCharArray()){ sb[idx].append(ch); if(idx == 0) num = 1; // 추가 후 첫번째 sb일때 인덱스 추가 if(idx == numRows - 1) num = -1; // 추가 후 마지막 sb일때 인덱스 빼기 idx += nu

Naver Blog

JAVA_LeetCode 7_Reverse Integer

JAVA_LeetCode 7_Reverse Integer 풀이 class Solution { public int reverse(int x) { // int 범위를 벗어날 경우 0 반환, 아닌 경우 역순으로 수를 더해준다. long res = 0; while(x != 0){ res *= 10; res += (x % 10); x /= 10; } if(res < Math.pow(-2, 31) || res > Math.pow(2, 31)) return 0; return (int)res; } } * 출처 https://leetcode.com/problems/reverse-integer

Naver Blog

JAVA_LeetCode 3427_Sum of Variable Length Subarrays

JAVA_LeetCode 3427_Sum of Variable Length Subarrays 풀이 class Solution { public int subarraySum(int[] nums) { // 하위 배열의 시작지점이 max(0, i - nums[i])이므로, 시작지점을 구해서 i까지의 요소 값을 더해준다. int res = 0, temp = 0; for(int i = 0; i < nums.length; i++){ temp = Math.max(0, i - nums[i]); while(temp <= i){ res += nums[temp]; temp++; } } return res; } } * 출처 https://leetcode.com/problems/sum-of-variable-length-subarrays

Naver Blog

JAVA_LeetCode 3432_Count Partitions with Even Sum Difference

JAVA_LeetCode 3432_Count Partitions with Even Sum Difference 풀이 class Solution { public int countPartitions(int[] nums) { // 총합을 구하고, 배열을 나누면서 양쪽 배열 요소 값 합 차가 2로 나눴을 때 0인 경우를 찾는다. int tot = 0, cnt = 0, left = 0, right = 0; for(int num : nums) tot += num; for(int i = 0; i < nums.length - 1; i++){ left += nums[i]; right = tot - left; if((left - right) % 2 == 0) cnt++; } return cnt; } } * 출처 https://leetcode.com/problems/count-partitions-with-even-sum-difference

Naver Blog

JAVA_LeetCode 3438_Find Valid Pair of Adjacent Digits in String

JAVA_LeetCode 3438_Find Valid Pair of Adjacent Digits in String 풀이 class Solution { public String findValidPair(String s) { // hashmap으로 key-value로 숫자를 체크하고, 반복해서 앞뒤가 다른지 확인하면서 map의 value와 s의 비교 숫자가 같은 경우 현재 위치의 문자열을 반환한다. HashMap<Character, Integer> map = new HashMap<>(); char ch; for(int i = 0; i < s.length(); i++){ ch = s.charAt(i); map.put(ch, map.getOrDefault(ch, 0) + 1); } for(int i = 1; i < s.length(); i++){ if(s.charAt(i) == s.charAt(i - 1)) continue; if(map.get(s.charAt(i)) == s.charAt(

Naver Blog

JAVA_LeetCode 3442_Maximum Difference Between Even and Odd Frequency I

JAVA_LeetCode 3442_Maximum Difference Between Even and Odd Frequency I 풀이 class Solution { public int maxDifference(String s) { // key별 중복횟수를 담고, 빈도에 따라 값을 초기화하고 비교한다. int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; Map<Character, Integer> map = new HashMap<>(); for(char ch : s.toCharArray()) map.put(ch, map.getOrDefault(ch, 0) + 1); for(int num : map.values()) { if(num % 2 == 1) max = Math.max(max, num); else min = Math.min(min, num); } return max - min; } } * 출처 https://leetcode.com/prob

Naver Blog

JAVA_LeetCode 3452_Sum of Good Numbers

JAVA_LeetCode 3452_Sum of Good Numbers 풀이 class Solution { public int sumOfGoodNumbers(int[] nums, int k) { // 각 인덱스별 num[i]가 num[i + k], nums[i - k]보다 큰지 확인한다. int sum = 0, len = nums.length; boolean bool; for(int i = 0; i < len; i++){ bool = true; if((i - k >= 0 && nums[i] <= nums[i - k])) bool = false; if((i + k < len && nums[i] <= nums[i + k])) bool = false; if(bool) sum += nums[i]; } return sum; } } * 출처 https://leetcode.com/problems/sum-of-good-numbers

Naver Blog

JAVA_LeetCode 3456_Find Special Substring of Length K

JAVA_LeetCode 3456_Find Special Substring of Length K 풀이 class Solution { public boolean hasSpecialSubstring(String s, int k) { // 문자가 같은경우를 체크하되, 다른 경우 조건에 부합한지 체크한다. int cnt = 1; for(int i = 1; i < s.length(); i++){ if(s.charAt(i - 1) != s.charAt(i) && cnt == k) return true; if(s.charAt(i) != s.charAt(i - 1)) cnt = 0; cnt++; } return cnt == k; } } * 출처 https://leetcode.com/problems/find-special-substring-of-length-k

Naver Blog

JAVA_LeetCode 3461_Check If Digits Are Equal in String After Operations I

JAVA_LeetCode 3461_Check If Digits Are Equal in String After Operations I 풀이 class Solution { public boolean hasSameDigits(String s) { // 2자리가 될때까지 반복해서 인덱스 기준 앞,뒤의 문자를 숫자로 만들어서 10으로 나눈 값을 문자열로 누적시킨다. int num = 0; while (s.length() > 2) { StringBuilder sb= new StringBuilder(); for (int i = 0; i < s.length() - 1; i++) { num = (s.charAt(i) - '0' + s.charAt(i + 1) - '0') % 10; sb.append(num); } s = sb.toString(); } return s.charAt(0) == s.charAt(1); } } * 출처 https://leetcode.com/problems/check-if-d

Naver Blog

JAVA_LeetCode 3467_Transform Array by Parity

JAVA_LeetCode 3467_Transform Array by Parity 풀이 class Solution { public int[] transformArray(int[] nums) { // 짝, 홀수 0, 1로 변경하고 정렬한다. for(int i = 0; i < nums.length; i++){ if(nums[i] % 2 == 0) nums[i] = 0; else nums[i] = 1; } Arrays.sort(nums); return nums; } } * 출처 https://leetcode.com/problems/transform-array-by-parity

Naver Blog

JAVA_LeetCode 3471_Find the Largest Almost Missing Integer

JAVA_LeetCode 3471_Find the Largest Almost Missing Integer 풀이 class Solution { public int largestInteger(int[] nums, int k) { // map과 set을 이용하여 하위배열에서 나온 숫자를 체크한다음, 횟수가 1인 수중 가장 큰 값을, 없으면 -1을 반환한다. Map<Integer, Integer> map = new HashMap<>(); Set<Integer> set; int max = -1; for(int i = 0; i <= nums.length - k; i++){ set = new HashSet<>(); for(int j = i; j < i + k; j++) set.add(nums[j]); for(int num : set) map.put(num, map.getOrDefault(num, 0) + 1); } for(Map.Entry<Integer, Integer> entry : map.e

Naver Blog

JAVA_LeetCode 3477_Fruits Into Baskets II

JAVA_LeetCode 3477_Fruits Into Baskets II 풀이 class Solution { public int numOfUnplacedFruits(int[] fruits, int[] baskets) { // 인덱스별 조건에 부합되는 수를 차례대로 없애가면서 체크한다. int cnt = 0, len = fruits.length; Set<Integer> set = new HashSet(); for(int i = 0; i < len; i++){ for(int j = 0; j < len; j++){ if(fruits[i] <= baskets[j] && !set.contains(j)){ set.add(j); cnt++; break; } } } return len - cnt; } } * 출처 https://leetcode.com/problems/fruits-into-baskets-ii

Naver Blog

JAVA_LeetCode 3483_Unique 3-Digit Even Numbers

JAVA_LeetCode 3483_Unique 3-Digit Even Numbers 풀이 class Solution { public int totalNumbers(int[] digits) { // 맨앞자리는 0이 될수 없고, 반복문중 동일한 인덱스는 제외하며, 현재 수가 짝수인경우를 찾는다. int len = digits.length; Set<String> set = new HashSet<>(); for(int i = 0; i < len; i++){ if(digits[i] == 0) continue; for(int j = 0; j < len; j++){ if(i == j) continue; for(int k = 0; k < len; k++){ if(k != i && k != j && digits[k] % 2 == 0) set.add("" + digits[i] + digits[j] + digits[k]); } } } return set.size(); } } * 출처 https://le

Naver Blog

JAVA_LeetCode 3487_Maximum Unique Subarray Sum After Deletion

JAVA_LeetCode 3487_Maximum Unique Subarray Sum After Deletion 풀이 class Solution { public int maxSum(int[] nums) { // set으로 중복을 제외하고 해당 수가 합이 최대화가 되기 위해 음수를 제외한다. int sum = 0, max = Integer.MIN_VALUE; Set<Integer> set = new HashSet<>(); for(int num : nums){ if(num > 0 && !set.contains(num)){ sum += num; set.add(num); }else if(num <= 0) max = Math.max(max, num); } return sum == 0 ? max : sum; } } * 출처 https://leetcode.com/problems/maximum-unique-subarray-sum-after-deletion

Naver Blog

JAVA_LeetCode 3492_Maximum Containers on a Ship

JAVA_LeetCode 3492_Maximum Containers on a Ship 풀이 class Solution { public int maxContainers(int n, int w, int maxWeight) { // maxWeight를 w로 나눈것과 n * n 중 작은 값을 반환한다. return Math.min(maxWeight / w, n * n); } } * 출처 https://leetcode.com/problems/maximum-containers-on-a-ship

Naver Blog

JAVA_LeetCode 3379_Transformed Array

JAVA_LeetCode 3379_Transformed Array 풀이 class Solution { public int[] constructTransformedArray(int[] nums) { // 요소값 기준 조건별 인덱스를 적용한다. int len = nums.length; int[] arr = new int[len]; for(int i = 0; i < len; i++){ if(nums[i] == 0) arr[i] = nums[i]; else if(nums[i] > 0) arr[i] = nums[(i + nums[i]) % len]; else arr[i] = nums[(((len + i + nums[i]) % len) + len) % len]; } return arr; } } * 출처 https://leetcode.com/problems/transformed-array

Naver Blog

JAVA_LeetCode 3386_Button with Longest Push Time

JAVA_LeetCode 3386_Button with Longest Push Time 풀이 class Solution { public int buttonWithLongestTime(int[][] events) { // 인접한 2차원 배열 중 버튼 시간 차가 같은 경우 최소값 / 가장 긴 경우를 체크한다. int res = 0, diff = 0, temp = 0, val = 0; for(int[] event: events){ diff = event[1] - val; if(diff == temp) res = Math.min(res, event[0]); else if(diff > temp){ temp = diff; res = event[0]; } val = event[1]; } return res; } } * 출처 https://leetcode.com/problems/button-with-longest-push-time

Naver Blog

JAVA_LeetCode 3392_Count Subarrays of Length Three With a Condition

JAVA_LeetCode 3392_Count Subarrays of Length Three With a Condition 풀이 class Solution { public int countSubarrays(int[] nums) { // 중간값이 양 값 합의 2배일경우 체크한다. int res = 0, len = nums.length; for(int i = 1; i < len - 1; i++){ if(nums[i] == (nums[i - 1] + nums[i + 1]) * 2) res++; } return res; } } * 출처 https://leetcode.com/problems/count-subarrays-of-length-three-with-a-condition

Naver Blog

JAVA_LeetCode 222_Count Complete Tree Nodes

JAVA_LeetCode 222_Count Complete Tree Nodes 풀이 /** * 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 int countNodes(TreeNode root) { // 현재 노드가 null이면 0을, 아닌 경우 현 노드 기준 좌우 노드를 파라미터로 받는다. if(root == null) return 0; return 1 + countNodes(ro

Naver Blog

JAVA_LeetCode 2864_Maximum Odd Binary Number

JAVA_LeetCode 2864_Maximum Odd Binary Number 풀이 class Solution { public String maximumOddBinaryNumber(String s) { // 1이 한개 이상 포함되어 있으므로, 0과 1을 체크해서 문자열로 더한다. int num = 0, num2 =0; for(char ch : s.toCharArray()){ if(ch == '1') num++; else num2++; } return "1".repeat(num - 1) + "0".repeat(num2) + "1"; } } * 출처 https://leetcode.com/problems/maximum-odd-binary-number

Naver Blog

JAVA_LeetCode 3005_Count Elements With Maximum Frequency

JAVA_LeetCode 3005_Count Elements With Maximum Frequency 풀이 class Solution { public int maxFrequencyElements(int[] nums) { // key별 개수를 체크한다음, 최대빈도를 따로 저장하여 이후 비교해서 같은 경우 해당 개수만큼 더해준다. HashMap<Integer, Integer> map = new HashMap<>(); int max = 0, cnt = 0; for(int i = 0; i < nums.length; i++){ map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); max = Math.max(max, map.get(nums[i])); } for(int keys : map.keySet()){ if(map.get(keys) == max) cnt += max; } return cnt; } } * 출처 https://leetcode.com/pro

Naver Blog

JAVA_LeetCode 3042_Count Prefix and Suffix Pairs I

JAVA_LeetCode 3042_Count Prefix and Suffix Pairs I 풀이 class Solution { public int countPrefixSuffixPairs(String[] words) { // 중복 for문에서 이전 문자가 접두사이며, 접미사인지 확인한다. int cnt = 0; for(int i = 0; i < words.length; i++){ for(int j = i + 1; j < words.length; j++){ if(words[j].indexOf(words[i]) == 0 && words[j].lastIndexOf(words[i]) == (words[j].length() - words[i].length())) cnt++; } } return cnt; } } * 출처 https://leetcode.com/problems/count-prefix-and-suffix-pairs-i

Naver Blog

JAVA_LeetCode 3396_Minimum Number of Operations to Make Elements in Array Distinct

JAVA_LeetCode 3396_Minimum Number of Operations to Make Elements in Array Distinct 풀이 class Solution { public int minimumOperations(int[] nums) { // set을 이용해서 중복 요소가 발견되는 경우 3으로 나눈 몫을 반환한다. Set<Integer> set = new HashSet<>(); for(int i = nums.length - 1; i >= 0; i--){ if(!set.contains(nums[i])) set.add(nums[i]); else return (i + 3) / 3; } return 0; } } * 출처 https://leetcode.com/problems/minimum-number-of-operations-to-make-elements-in-array-distinct

Naver Blog

JAVA_LeetCode 3402_Minimum Operations to Make Columns Strictly Increasing

풀이 class Solution { public int minimumOperations(int[][] grid) { // 각 열별 증가값(위에서 아래로 증가)을 독립적으로 체크해서 더해줘야함 int sum = 0; for(int j = 0; j < grid[0].length; j++){ for(int i = 1; i < grid.length; i++){ if(grid[i][j] <= grid[i - 1][j]){ sum += grid[i - 1][j] - grid[i][j] + 1; grid[i][j] = grid[i - 1][j] + 1; } } } return sum; } } * 출처 https://leetcode.com/problems/minimum-operations-to-make-columns-strictly-increasing

Naver Blog

JAVA_LeetCode 3407_Substring Matching Pattern

JAVA_LeetCode 3407_Substring Matching Pattern 풀이 class Solution { public boolean hasMatch(String s, String p) { // p의 *을 기준으로 문자 체크하기 int idx = p.indexOf("*"); if(s.indexOf(p.substring(0, idx)) != -1 && s.indexOf(p.substring(idx + 1), s.indexOf(p.substring(0, idx)) + idx) != -1) return true; return false; } } * 출처 https://leetcode.com/problems/substring-matching-pattern

Naver Blog

JAVA_LeetCode 3411_Maximum Subarray With Equal Products

JAVA_LeetCode 3411_Maximum Subarray With Equal Products 풀이 class Solution { // 최대 공약수 public int gcd(int a, int b){ return b == 0 ? a : gcd(b, a % b); } // 최소 공배수 public int lcm(int a, int b){ return (a / gcd(a, b)) * b; } public int maxLength(int[] nums) { // 시작지점으로부터 각 조건에 부합한 요소를 계산한다. int maxLen = 0, len = nums.length, gcd = 0, lcm = 0, prod = 0; for(int i = 0; i < len; i++){ gcd = nums[i]; lcm = nums[i]; prod = nums[i]; for(int j = i + 1; j < len; j++) { gcd = gcd(gcd, nums[j]); lcm = lcm(l

Naver Blog

JAVA_LeetCode 3417_Zigzag Grid Traversal With Skip

JAVA_LeetCode 3417_Zigzag Grid Traversal With Skip 풀이 class Solution { public List<Integer> zigzagTraversal(int[][] grid) { // 짝수행에는 행+열 값을 2로 나눴을 때 0, 홀수행에선 1로 나오는 패턴 List<Integer> list = new ArrayList<>(); for(int i = 0; i < grid.length; i++){ if(i % 2 == 0){ for(int j = 0; j < grid[0].length; j++){ if((i + j) % 2 == 0) list.add(grid[i][j]); } }else{ for(int j = grid[0].length - 1; j >= 0; j--){ if((i + j) % 2 == 0) list.add(grid[i][j]); } } } return list; } } * 출처 https://leetcode.com/problem

Naver Blog

JAVA_LeetCode 3423_Maximum Difference Between Adjacent Elements in a Circular Array

JAVA_LeetCode 3423_Maximum Difference Between Adjacent Elements in a Circular Array 풀이 class Solution { public int maxAdjacentDistance(int[] nums) { // 순환하면서 양쪽 값의 절대차를 구하고 기존 최대값 중 가장 큰 값을 찾는다. int max = 0, num = 0; for(int i = 0; i < nums.length; i++){ num = Math.abs(nums[i] - nums[(i + 1) % nums.length]); max = Math.max(max, num); } return max; } } * 출처 https://leetcode.com/problems/maximum-difference-between-adjacent-elements-in-a-circular-array

Naver Blog

JAVA_LeetCode 3364_Minimum Positive Sum Subarray

JAVA_LeetCode 3364_Minimum Positive Sum Subarray 풀이 class Solution { public int minimumSumSubarray(List<Integer> nums, int l, int r) { // l ~ r만큼 반복해서 배열의 합을 구하고, 각 배열별 합계가 0보다 크며 해당 길이의 모든 가능한 배열을 찾아서 합계로 구한다. int min = Integer.MAX_VALUE, sum = 0; for (int k = l; k <= r; k++){ sum = 0; for(int i = 0; i < k; i++) sum += nums.get(i); if(sum > 0) min = Math.min(min, sum); // 슬라이딩 윈도우를 이용하여 왼쪽 끝 값을 밀어낸다. for(int i = k; i < nums.size(); i++){ sum -= nums.get(i - k); sum += nums.get(i); if(sum > 0) m

Naver Blog

JAVA_LeetCode 3370_mallest Number With All Set Bits

JAVA_LeetCode 3370_mallest Number With All Set Bits 풀이 class Solution { public int smallestNumber(int n) { // 2진수이되, n보다 크고, 이진표현이 모두 1인경우 int res = 1; while(res < n + 1) res <<= 1; return res - 1; } } * 출처 https://leetcode.com/problems/smallest-number-with-all-set-bits

Naver Blog

JAVA_LeetCode 3375_Minimum Operations to Make Array Values Equal to K

JAVA_LeetCode 3375_Minimum Operations to Make Array Values Equal to K 풀이 class Solution { public int minOperations(int[] nums, int k) { // 배열 요소중 가장 작은 값이 k보다 같거나 크고, 중복값 제거한 요소 개수를 체크한다. int min = Integer.MAX_VALUE; for(int num : nums) min = Math.min(min, num); if(min < k) return -1; HashSet<Integer> set = new HashSet<>(); for(int num : nums) set.add(num); // 만약, 최소값과 k가 같은경우 1을 빼준다. return set.size() - (min == k ? 1 : 0); } } * 출처 https://leetcode.com/problems/minimum-operations-to-make-array-

Naver Blog

JAVA_LeetCode 2506_Count Pairs Of Similar Strings

JAVA_LeetCode 2506_Count Pairs Of Similar Strings 풀이 class Solution { public int similarPairs(String[] words) { // set을 이용하여 중복값을 제거한 문자를 체크하여 비교한다. List<Set<Character>> list = new ArrayList<>(); Set<Character> set = null; int cnt = 0; for(int i = 0; i < words.length; i++){ set = new HashSet<>(); for(int j = 0; j <words[i].length(); j++) set.add(words[i].charAt(j)); list.add(set); } for(int i = 0; i < list.size(); i++){ for(int j = i + 1; j < list.size(); j++){ if(list.get(i).equals(list.get(j))

Naver Blog

JAVA_LeetCode 2511_Maximum Enemy Forts That Can Be Captured

JAVA_LeetCode 2511_Maximum Enemy Forts That Can Be Captured 풀이 class Solution { public int captureForts(int[] forts) { // 시작 위치를 찾은 다음, 최대값을 도출한다. int prev = -2, pos = 0, max = 0; for(int i = 0; i < forts.length; i++){ if(forts[i] == 1 || forts[i] == -1){ if(prev == -2){ prev = forts[i]; pos = i; }else if(prev != forts[i]){ max = Math.max(max, i - pos - 1); prev = forts[i]; pos = i; }else pos = i; } } return max; } } * 출처 https://leetcode.com/problems/maximum-enemy-forts-that-can-be-captured

Naver Blog

JAVA_LeetCode 2515_Shortest Distance to Target String in a Circular Array

JAVA_LeetCode 2515_Shortest Distance to Target String in a Circular Array 풀이 class Solution { public int closetTarget(String[] words, String target, int startIndex) { // 같은 문자열을 찾으면 현 인덱스 기준, 절대값을 찾아서 인덱스 차의 최소값을 체크한다. int res = Integer.MAX_VALUE, len = words.length; for (int i = 0; i < words.length; i++) { if (target.equals(words[i])) { res = Math.min(res, Math.abs(i - startIndex)); res = Math.min(res, len - Math.abs(i - startIndex)); } } return res == Integer.MAX_VALUE ? -1 : res; } } * 출처 htt

Naver Blog

JAVA_LeetCode 2520_Count the Digits That Divide a Number

JAVA_LeetCode 2520_Count the Digits That Divide a Number 풀이 class Solution { public int countDigits(int num) { // 10으로 나눈 나머지로 값을 나눴을때 0인경우를 체크한다. int res = 0, target = num, digit = 0; while(target > 0) { digit = target % 10; target /= 10; if(num % digit == 0) res++; } return res; } } * 출처 https://leetcode.com/problems/count-the-digits-that-divide-a-number

Naver Blog

JAVA_LeetCode 2525_Categorize Box According to Criteria

JAVA_LeetCode 2525_Categorize Box According to Criteria 풀이 class Solution { public String categorizeBox(int length, int width, int height, int mass) { // 각 조건에 맞춰 논리값 초기화해준다음, 해당 값에 맞춰 반환한다. boolean isBulky = 1000000000 <= ((long)length * width * height) || length >= 10000 || width >= 10000 || height >= 10000; boolean isHeavy = mass >= 100; return isBulky && isHeavy ? "Both" : !isBulky && !isHeavy ? "Neither" : isBulky ? "Bulky" : "Heavy"; } } * 출처 https://leetcode.com/problems/categorize-box-ac

Naver Blog

JAVA_LeetCode 2529_Maximum Count of Positive Integer and Negative Integer

JAVA_LeetCode 2529_Maximum Count of Positive Integer and Negative Integer 풀이 class Solution { public int maximumCount(int[] nums) { // 음, 양수 값을 체크해서 횟수를 저장한다음 최댓값을 반환한다. int num1 = 0, num2 = 0; for(int num : nums){ if(num > 0) num1++; if(num < 0) num2++; } return num1 > num2 ? num1 : num2; } } * 출처 https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer

Naver Blog

JAVA_LeetCode 2535_Difference Between Element Sum and Digit Sum of an Array

JAVA_LeetCode 2535_Difference Between Element Sum and Digit Sum of an Array 풀이 class Solution { public int differenceOfSum(int[] nums) { // 총 값과 10으로 나눈값을 모두 더한 값을 비교하여 절대값을 반환한다. int sum = 0, sum2 = 0; for(int num : nums) { sum += num; while(num != 0) { sum2 += num % 10; num /= 10; } } return Math.abs(sum - sum2); } } * 출처 https://leetcode.com/problems/difference-between-element-sum-and-digit-sum-of-an-array

Naver Blog

JAVA_LeetCode 2540_Minimum Common Value

JAVA_LeetCode 2540_Minimum Common Value 풀이 class Solution { public int getCommon(int[] nums1, int[] nums2) { // key : 값, value : 개수로 넣은 다음, 두 배열이 오름차순으로 정렬되어 있으므로 동일한 값이 있으면 반환한다. HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums1) map.put(num, map.getOrDefault(num, 0) + 1); for (int num : nums2){ if(map.containsKey(num) && map.get(num) > 0) return num; } return -1; } } * 출처 https://leetcode.com/problems/minimum-common-value

Naver Blog

JAVA_LeetCode 2544_Alternating Digit Sum

JAVA_LeetCode 2544_Alternating Digit Sum 풀이 class Solution { public int alternateDigitSum(int n) { // 숫자를 문자열로 만들어서 반복문에서 홀/짝수 여부에 맞춰 빼거나 더해준다. String str = Integer.toString(n); int sum = 0; for (int i = 0; i < str.length(); i++) { if (i % 2 == 0) sum += str.charAt(i) - '0'; else sum -= str.charAt(i) - '0'; } return sum; } } * 출처 https://leetcode.com/problems/alternating-digit-sum

Naver Blog

JAVA_LeetCode 2549_Count Distinct Numbers on Board

JAVA_LeetCode 2549_Count Distinct Numbers on Board 풀이 class Solution { public int distinctIntegers(int n) { // 자기 자신과 나눴을 때 1이 남는 경우 set에 담아준다. Set<Integer> set = new HashSet<>(); set.add(n); while(n > 0){ for(int i = 1; i <= n; i++){ if(n % i == 1) set.add(i); } n--; } return set.size(); } } * 출처 https://leetcode.com/problems/count-distinct-numbers-on-board

Naver Blog

JAVA_LeetCode 2437_Number of Valid Clock Times

JAVA_LeetCode 2437_Number of Valid Clock Times 풀이 class Solution { public int countTime(String time) { // 시, 분 값에 따라 조건에 맞춰 곱하거나 값을 초기화해준다. int res = 1; if(time.charAt(0) == '?'){ if(time.charAt(1) >= '4' && time.charAt(1) <= '9') res *= 2; else res *= 3; } if(time.charAt(1) == '?'){ if(time.charAt(0) == '?') res = 24; else if(time.charAt(0) == '2') res *= 4; else res *= 10; } if(time.charAt(3) == '?') res *= 6; if(time.charAt(4) == '?' ) res *= 10; return res; } } * 출처 https://leetcode.com/prob

Naver Blog

JAVA_LeetCode 2441_Largest Positive Integer That Exists With Its Negative

JAVA_LeetCode 2441_Largest Positive Integer That Exists With Its Negative 풀이 class Solution { public int findMaxK(int[] nums) { // 중복값중 가장 큰값을 추출한다. int res = -1; HashSet<Integer> set = new HashSet<>(); for (int num : nums) set.add(num); for (int num : nums){ if (num > 0 && set.contains(-num)) res = Math.max(res, num); } return res; } } * 출처 https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative

Naver Blog

JAVA_LeetCode 2446_Determine if Two Events Have Conflict

JAVA_LeetCode 2446_Determine if Two Events Have Conflict 풀이 class Solution { public boolean haveConflict(String[] event1, String[] event2) { // 양값을 비교하여 true를 반환한다. return event1[1].compareTo(event2[0]) >= 0 && event2[1].compareTo(event1[0]) >= 0; } } * 출처 https://leetcode.com/problems/determine-if-two-events-have-conflict

Naver Blog

JAVA_LeetCode 2451_Odd String Difference

JAVA_LeetCode 2451_Odd String Difference 풀이 class Solution { public String oddString(String[] words) { // hashmap의 key-value를 이용한 풀이법이다. HashMap<ArrayList<Integer>, ArrayList<String>> hm = new HashMap<>(); ArrayList<String> value = null; ArrayList<Integer> key = null; String str = null; for(int i = 0; i < words.length; i++){ str = words[i]; key = new ArrayList<>(); for(int j = 0; j < str.length() - 1; j++){ key.add(Integer.valueOf(str.charAt(j + 1)) - Integer.valueOf(str.charAt(j))); } if(hm.con

1 2 3 4 5 6 7 8 9 10