joonbread의 등록된 링크

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

Naver Blog

JAVA_LeetCode 2455_Average Value of Even Numbers That Are Divisible by Three

JAVA_LeetCode 2455_Average Value of Even Numbers That Are Divisible by Three 풀이 class Solution { public int averageValue(int[] nums) { // 6으로 나눠 떨어지는 수를 구해서 더하고 더한 값의 수만큼 나눈다. int sum = 0, cnt = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] % 6 == 0){ sum += nums[i]; cnt++; } } if(cnt == 0) return 0; return sum / cnt; } } * 출처 https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three

Naver Blog

JAVA_LeetCode 2460_Apply Operations to an Array

JAVA_LeetCode 2460_Apply Operations to an Array 풀이 class Solution { public int[] applyOperations(int[] nums) { // 동일 요소를 발견하면 현 인덱스는 2를 곱하고 같은값을 가진 인덱스에 0을 넣어준다. int[] arr = new int[nums.length]; for(int i = 0; i < nums.length - 1; i++){ if (nums[i] == nums[i + 1]){ nums[i] = nums[i] * 2; nums[i + 1] = 0; } } // 0이 아닌건 앞으로 보내고 그 이후 요소는 0으로 채운다. int cnt = 0; for (int i : nums) { if (i > 0) { arr[cnt++] = i; } } for(int i = cnt; i < arr.length; i++){ arr[cnt++] = 0; } return arr; } } * 출처 https://

Naver Blog

JAVA_LeetCode 2465_Number of Distinct Averages

JAVA_LeetCode 2465_Number of Distinct Averages 풀이 class Solution { public int distinctAverages(int[] nums) { // 정렬 후 양 끝 값 평균을 계속해서 구하면서 set에 넣어준다. HashSet<Float> set = new HashSet<>(); Arrays.sort(nums); float num = 0; int cnt = 0; while(cnt != nums.length / 2) { num = ((float)(nums[cnt] + nums[nums.length - cnt - 1]) / 2.0f); cnt++; set.add(num); } return set.size(); } } 양 끝단의 값을 구하면서, set의 중복값 제거를 이용한 풀이법이다. * 출처 https://leetcode.com/problems/number-of-distinct-averages

Naver Blog

JAVA_LeetCode 2469_Convert the Temperature

JAVA_LeetCode 2469_Convert the Temperature 풀이 class Solution { public double[] convertTemperature(double celsius) { // 공식 값 그대로 반환 return new double[]{celsius + 273.15, 1.80 * celsius + 32.00}; } } * 출처 https://leetcode.com/problems/convert-the-temperature

Naver Blog

JAVA_LeetCode 2475_Number of Unequal Triplets in Array

JAVA_LeetCode 2475_Number of Unequal Triplets in Array 풀이 class Solution { public int unequalTriplets(int[] nums) { // 정렬한다음, 삼중항 조건에 맞는 횟수 체크한다. Arrays.sort(nums); int cnt = 0, len = nums.length; for(int i = 0; i < len - 2; i++){ for(int j = i + 1; j < len - 1; j++){ for(int k = j + 1; k < len; k++){ if(nums[j] != nums[i] && nums[k] != nums[j]) cnt++; } } } return cnt; } } 순차적으로 i < j < k 조건에 맞는 값을 찾는다. * 출처 https://leetcode.com/problems/number-of-unequal-triplets-in-array

Naver Blog

JAVA_LeetCode 2481_Minimum Cuts to Divide a Circle

JAVA_LeetCode 2481_Minimum Cuts to Divide a Circle 풀이 class Solution { public int numberOfCuts(int n) { // 하나면 안자르고, 짝수면 n을 2로 나눈 수, 나머지는 그만큼 자른다. if(n == 1) return 0; if(n % 2 == 0) return n / 2; return n; } } * 출처 https://leetcode.com/problems/minimum-cuts-to-divide-a-circle

Naver Blog

JAVA_LeetCode 2485_Find the Pivot Integer

JAVA_LeetCode 2485_Find the Pivot Integer 풀이 class Solution { public int pivotInteger(int n) { // 먼저 총합을 구한 뒤, 현재 합과 총합의 차이가 현재 정수의 2배와 같은 지 확인한다. int res = 1, sum1 = n * (n + 1) / 2, sum2 = 0; while(res <= n){ sum2 = res * (res + 1) / 2; if(sum2 == (sum1 + res - sum2)) return res; res++; } return -1; } } * 출처 https://leetcode.com/problems/find-the-pivot-integer

Naver Blog

JAVA_LeetCode 2490_Circular Sentence

JAVA_LeetCode 2490_Circular Sentence 풀이 class Solution { public boolean isCircularSentence(String sentence) { // 문자열의 마지막 문자와 다음 문자열의 첫번째 문자가 일치하는지 확인한다. int len = sentence.length(); for (int i = 0; i < len; i++) { if(i == len - 1 && (sentence.charAt(0) != sentence.charAt(len - 1))) return false; else if(sentence.charAt(i) == ' ' && (sentence.charAt(i - 1) != sentence.charAt(i + 1))) return false; } return true; } } * 출처 https://leetcode.com/problems/circular-sentence

Naver Blog

JAVA_LeetCode 2496_Maximum Value of a String in an Array

JAVA_LeetCode 2496_Maximum Value of a String in an Array 풀이 class Solution { public int maximumValue(String[] strs) { // 문자 여부에 따라 길이 또는 숫자를 가지고 최대값을 구한다. int res = 0, max = 0; for(int i = 0; i < strs.length; i++){ max = strs[i].matches("\\d+") ? Integer.parseInt(strs[i]) : strs[i].length(); res = Math.max(res, max); } return res; } } * 출처 https://leetcode.com/problems/maximum-value-of-a-string-in-an-array

Naver Blog

JAVA_LeetCode 2500_Delete Greatest Value in Each Row

JAVA_LeetCode 2500_Delete Greatest Value in Each Row 풀이 class Solution { public int deleteGreatestValue(int[][] grid) { // 정렬 후 각 행마다 최대값을 찾아 더해준다. int colLen = grid[0].length, rowLen = grid.length, res = 0, max = 0; for(int[] arr : grid) Arrays.sort(arr); for(int col = 0; col < colLen; col++){ max = 0; for(int row = 0; row < rowLen; row++) max = Math.max(max, grid[row][col]); res += max; } return res; } } * 출처 https://leetcode.com/problems/delete-greatest-value-in-each-row

Naver Blog

SQL_LeetCode 1978_Employees Whose Manager Left the Company

SQL_LeetCode 1978_Employees Whose Manager Left the Company 풀이 -- ORACLE, MYSQL, MSSQL SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE SALARY < 30000 AND MANAGER_ID IS NOT NULL AND MANAGER_ID NOT IN( SELECT EMPLOYEE_ID FROM EMPLOYEES ) ORDER BY EMPLOYEE_ID; * 출처 https://leetcode.com/problems/employees-whose-manager-left-the-company

Naver Blog

JAVA_LeetCode 2373_Largest Local Values in a Matrix

JAVA_LeetCode 2373_Largest Local Values in a Matrix 풀이 class Solution { public int[][] largestLocal(int[][] grid) { // 행렬의 중첩 루프를 사용하여 최대값을 구한다. int len = grid.length, temp = 0; int [][] res = new int[len - 2][len - 2]; for(int i = 1; i < len - 1; ++i){ for(int j = 1; j < len - 1; ++j){ temp = 0; for(int k = i - 1; k <= i + 1; ++k){ for(int m = j - 1; m <= j + 1; ++m){ temp = Math.max(temp, grid[k][m]); } } res[i - 1][j - 1] = temp; } } return res; } } * 출처 https://leetcode.com/problems/largest-

Naver Blog

JAVA_LeetCode 2379_Minimum Recolors to Get K Consecutive Black Blocks

JAVA_LeetCode 2379_Minimum Recolors to Get K Consecutive Black Blocks 풀이 class Solution { public int minimumRecolors(String blocks, int k) { // k 길이중 'W'를 찾은 값과 최소값을 비교하여 가장 최소값을 반환한다. int res = Integer.MAX_VALUE, min = 0; for(int i = 0; i < blocks.length() - k + 1; i++) { min = 0; for(int j = i; j < i + k; j++) { if(blocks.charAt(j) == 'W') min++; } res = Math.min(min, res); } return res; } } * 출처 https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks

Naver Blog

JAVA_LeetCode 2383_Minimum Hours of Training to Win a Competition

JAVA_LeetCode 2383_Minimum Hours of Training to Win a Competition 풀이 class Solution { public int minNumberOfHours(int initialEnergy, int initialExperience, int[] energy, int[] experience) { // 모든 에너지에서 초기 에너지 + 1을 뺀다음, 경험치 필요 여부에 따라 계산한다. int res = 0, res2 = 0, num = 0, diff = 0; for(int i = 0; i < energy.length; i++) num += energy[i]; if(initialEnergy <= num) res = num - initialEnergy + 1; for(int i = 0; i < experience.length; i++){ if(initialExperience <= experience[i]) { diff = experience[i]

Naver Blog

JAVA_LeetCode 2389_Longest Subsequence With Limited Sum

JAVA_LeetCode 2389_Longest Subsequence With Limited Sum 풀이 class Solution { public int[] answerQueries(int[] nums, int[] queries) { // 오름차순 정렬 후 순차적으로 값을 합치면서 부분 수열의 최대 크기를 체크한다. int len = queries.length, len2 = nums.length, num = 0; int[] res = new int[len]; Arrays.sort(nums); for(int i = 0; i < len; i++){ num = 0; for(int j = 0; j < len2; j++){ num += nums[j]; if (num > queries[i]){ res[i] = j; break; }else if(j + 1 == len2) res[i] = len2; } } return res; } } * 출처 https://leetcode.com/problems

Naver Blog

JAVA_LeetCode 2395_Find Subarrays With Equal Sum

JAVA_LeetCode 2395_Find Subarrays With Equal Sum 풀이 class Solution { public boolean findSubarrays(int[] nums) { // 2개의 부분 배열을 두고 set을 이용하여 중복여부를 판단한다. HashSet<Integer> set = new HashSet<>(); for(int i = 0; i < nums.length - 1; i++){ if(set.contains(nums[i] + nums[i + 1])) return true; else set.add(nums[i] + nums[i + 1]); } return false; } } * 출처 https://leetcode.com/problems/find-subarrays-with-equal-sum

Naver Blog

JAVA_LeetCode 2399_Check Distances Between Same Letters

JAVA_LeetCode 2399_Check Distances Between Same Letters 풀이 class Solution { public boolean checkDistances(String s, int[] distance) { // 각 단어를 map에 담은 다음 특정 단어가 map에 있을 경우 // 양 단어간 index차이를 구하고 배열 요소와 비교하여 아닌경우 값을 반환한다. Map<Character,Integer> map = new HashMap<>(); int diff = 0, idx = 0; char ch; for(int i = 0; i < s.length(); i++){ ch = s.charAt(i); if(!map.containsKey(ch)) map.put(ch, i); else{ idx = map.get(ch); diff = i - idx - 1; if(distance[ch - 'a'] != diff) return false; } } return true;

Naver Blog

JAVA_LeetCode 2404_Most Frequent Even Element

JAVA_LeetCode 2404_Most Frequent Even Element 풀이 class Solution { public int mostFrequentEven(int[] nums) { // 짝수 횟수를 체크해서 최대값 중 최대개수가 동점인 경우 최저값을 체크한다. HashMap<Integer,Integer> map = new HashMap<>(); int ans = -1, max = 0, temp = 0; for(int num : nums){ if (num % 2 == 0){ map.put(num, map.getOrDefault(num, 0) + 1); temp = map.get(num); if (temp > max || (temp == max && num < ans)){ max = temp; ans = num; } } } return ans; } } * 출처 https://leetcode.com/problems/most-frequent-even-element

Naver Blog

JAVA_LeetCode 2409_Count Days Spent Together

JAVA_LeetCode 2409_Count Days Spent Together 풀이 class Solution { public int countDaysTogether(String arriveAlice, String leaveAlice, String arriveBob, String leaveBob) { // string의 compareTo를 이용하여 날짜 앞 뒤를 찾고, 값을 비교하여 일을 반환한다. int[] day = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int res = 0; String st = arriveAlice.compareTo(arriveBob) > 0 ? arriveAlice : arriveBob; String ed = leaveAlice.compareTo(leaveBob) > 0 ? leaveBob : leaveAlice; int stMon = Integer.parseInt(st.substri

Naver Blog

SQL_LeetCode 2413_Smallest Even Multiple

SQL_LeetCode 2413_Smallest Even Multiple 풀이 class Solution { public int smallestEvenMultiple(int n) { // 짝수 반환 홀수면 2를 곱한값을 반환한다. return n % 2 == 0 ? n : n * 2; } } * 출처 https://leetcode.com/problems/smallest-even-multiple

Naver Blog

SQL_LeetCode 2418_Sort the People

SQL_LeetCode 2418_Sort the People 풀이 class Solution { public String[] sortPeople(String[] names, int[] heights) { // height를 key로 이름을 넣고 height를 정렬해서 height별 이름을 추출한다. Map<Integer, String> map = new HashMap<>(); int n = names.length, j = 0; for (int i = 0; i < n; ++i) map.put(heights[i], names[i]); Arrays.sort(heights); for (int i = n - 1; i >= 0; i--) names[j++] = map.get(heights[i]); return names; } } * 출처 https://leetcode.com/problems/sort-the-people

Naver Blog

JAVA_LeetCode 2423_Remove Letter To Equalize Frequency

JAVA_LeetCode 2423_Remove Letter To Equalize Frequency 풀이 class Solution { public boolean equalFrequency(String word) { // hashmap으로 문자별 횟수를 센다음, 문자열에서 map의 문자를 추출한다. // map의 값을 컬렉션 형태로 set에 저장하여 크기가 1이면 true / 아닌 경우 재확인한다. HashMap<Character,Integer> map = new HashMap<>(); for(char ch : word.toCharArray()) map.put(ch, map.getOrDefault(ch, 0) + 1); for(int i = 0; i < word.length(); i++){ int cnt = map.get(word.charAt(i)); if(cnt - 1 != 0) map.put(word.charAt(i), cnt - 1); else map.remove(word.cha

Naver Blog

JAVA_LeetCode 2427_Number of Common Factors

JAVA_LeetCode 2427_Number of Common Factors 풀이 class Solution { public int commonFactors(int a, int b) { // 1부터 a, b중 최대값만큼 반복하여 두수 모두 나눴을때 0인경우를 체크한다. int res = 0; for(int i = 1; i <= Math.max(a, b); i++){ if(a % i == 0 && b % i == 0) res++; } return res; } } * 출처 https://leetcode.com/problems/number-of-common-factors

Naver Blog

JAVA_LeetCode 2432_The Employee That Worked on the Longest Task

JAVA_LeetCode 2432_The Employee That Worked on the Longest Task 풀이 class Solution { public int hardestWorker(int n, int[][] logs) { // 반복해서 배열별 2번째 요소를 비교한다음, 결과에 따라 값을 바꿔나간다. int id = logs[0][0], max = logs[0][1], diff = 0; for (int i = 1; i < logs.length; i++) { diff = logs[i][1] - logs[i - 1][1]; if(max < diff){ max = diff; id = logs[i][0]; }else if(max == diff) id = Math.min(id, logs[i][0]); } return id; } } * 출처 https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task

Naver Blog

JAVA_LeetCode 2319_Check if Matrix Is X-Matrix

JAVA_LeetCode 2319_Check if Matrix Is X-Matrix 풀이 class Solution { public boolean checkXMatrix(int[][] grid) { // 대각선은 i == j 또는 i == n - 1 - j일때를 의미 // 대각선에 0이 있거나, 아닌경우 0이 아닌경우를 체크한다. int len = grid.length; for(int i = 0; i < len; i++){ for(int j = 0; j < len; j++){ if(i == j || i == len - 1- j){ if(grid[i][j] == 0) return false; }else{ if(grid[i][j] != 0) return false; } } } return true; } } * 출처 https://leetcode.com/problems/check-if-matrix-is-x-matrix

Naver Blog

JAVA_LeetCode 2325_Decode the Message

JAVA_LeetCode 2325_Decode the Message 풀이 class Solution { public String decodeMessage(String key, String message) { // map에 문자별 값을 세팅한다음, message에서 해당 문자를 찾아서 이어붙인다. StringBuilder sb = new StringBuilder(); HashMap<Character, Character> map = new HashMap<>(); key = key.replace(" ",""); char str = 'a'; for(char ch : key.toCharArray()){ if(!map.containsKey(ch)) map.put(ch, str++); } for(char ch : message.toCharArray()){ if(!map.containsKey(ch)) sb.append(ch); else sb.append(map.get(ch)); } return s

Naver Blog

JAVA_LeetCode 2331_Evaluate Boolean Binary Tree

JAVA_LeetCode 2331_Evaluate Boolean Binary Tree 풀이 class Solution { public boolean evaluateTree(TreeNode root) { // 2보다 작으면, 논리값을, 2, 3일땐 리프노드 값의 연산값을 반환한다. if(root.val < 2) return root.val == 1; if(root.val == 2) return evaluateTree(root.left) || evaluateTree(root.right); return evaluateTree(root.left) && evaluateTree(root.right); } } * 출처 https://leetcode.com/problems/evaluate-boolean-binary-tree

Naver Blog

JAVA_LeetCode 2335_Minimum Amount of Time to Fill Cups

JAVA_LeetCode 2335_Minimum Amount of Time to Fill Cups 풀이 class Solution { public int fillCups(int[] amount) { // 배열의 가장 작은 수를 제외한 두 수가 0보다 작거나 같은경우 카운팅된 수를 반환한다. int cnt = 0; while(true){ Arrays.sort(amount); if(amount[2] <= 0 && amount[1] <= 0) break; amount[2]--; amount[1]--; cnt++; } return cnt; } } * 출처 https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups

Naver Blog

JAVA_LeetCode 2341_Maximum Number of Pairs in Array

JAVA_LeetCode 2341_Maximum Number of Pairs in Array 풀이 class Solution { public int[] numberOfPairs(int[] nums) { // 같은 값이 있는경우 삭제하고, 없을 경우 set에 추가해준다. Set<Integer> set = new HashSet<>(); int cnt = 0; for(int num : nums){ if(set.contains(num)) { cnt++; set.remove(num); }else set.add(num); } return new int[]{cnt, set.size()}; } } * 출처 https://leetcode.com/problems/maximum-number-of-pairs-in-array

Naver Blog

JAVA_LeetCode 2347_Best Poker Hand

JAVA_LeetCode 2347_Best Poker Hand 풀이 class Solution { public String bestHand(int[] ranks, char[] suits) { // 각 조건에 맞춰 반환 HashMap<Integer, Integer> map = new HashMap<>(); int cnt = 0; for(int i = 0; i < suits.length - 1; i++){ if(suits[i] != suits[i + 1]) break; if(i == 3) return "Flush"; } for(int i = 0; i < ranks.length; i++) { map.put(ranks[i], 1 + map.getOrDefault(ranks[i], 0)); if(map.get(ranks[i]) >= 3) return "Three of a Kind"; if(map.get(ranks[i]) > cnt) cnt = map.get(ranks[i]); } if(cnt

Naver Blog

JAVA_LeetCode 2351_First Letter to Appear Twice

JAVA_LeetCode 2351_First Letter to Appear Twice 풀이 class Solution { public char repeatedCharacter(String s) { // 중복된 값이 있을 경우 해당 값을 반환한다. HashSet<Character> set = new HashSet<>(); int len = s.length(); for(int i = 0; i < len; i++){ if(set.contains(s.charAt(i))) return s.charAt(i); set.add(s.charAt(i)); } return ' '; } } * 출처 https://leetcode.com/problems/first-letter-to-appear-twice

Naver Blog

JAVA_LeetCode 2357_Make Array Zero by Subtracting Equal Amounts

JAVA_LeetCode 2357_Make Array Zero by Subtracting Equal Amounts 풀이 class Solution { public int minimumOperations(int[] nums) { // 중복 제거 개수를 체크하여 반환한다. Set<Integer> set = new HashSet<Integer>(); for(int i : nums){ if(i > 0) set.add(i); } return set.size(); } } * 출처 https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts

Naver Blog

JAVA_LeetCode 2363_Merge Similar Items

JAVA_LeetCode 2363_Merge Similar Items 풀이 class Solution { public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) { // items1과 items2의 요소를 map에 담은다음, 동일한 값을 가진 가중치를 계속 누적시킨다. // 키별로 오름차순을 하기위해 treemap으로 만든다. TreeMap<Integer, Integer> map = new TreeMap<>(); List<List<Integer>> list = new ArrayList<>(); if(items1.length == 0 && items2.length == 0) return list; for(int[] item1: items1) map.put(item1[0], item1[1]); for(int[] item2: items2){ if(map.containsKey(item2[0])) map.put

Naver Blog

JAVA_LeetCode 2367_Number of Arithmetic Triplets

JAVA_LeetCode 2367_Number of Arithmetic Triplets 풀이 class Solution { public int arithmeticTriplets(int[] nums, int diff) { // 중복값을 제거, 요소에서 diff를 더한값과 2 * diff가 있는 경우를 체크한다. Set<Integer> set = new HashSet<>(); int cnt = 0; for(int num : nums) set.add(num); for(int num : nums){ if(set.contains(num + diff) && set.contains(num + (2 * diff))) cnt++; } return cnt; } } 삼중항의 조건에 맞추기 위해 num에 diff더한값과 diff 2번을 더한값이 포함된경우를 체크한다. * 출처 https://leetcode.com/problems/number-of-arithmetic-triplets

Naver Blog

SQL_LeetCode 1789_Primary Department for Each Employee

SQL_LeetCode 1789_Primary Department for Each Employee 풀이 -- ORACLE, MYSQL, MSSQL SELECT EMPLOYEE_ID , DEPARTMENT_ID FROM EMPLOYEE WHERE PRIMARY_FLAG = 'Y' OR EMPLOYEE_ID IN ( SELECT EMPLOYEE_ID FROM EMPLOYEE GROUP BY EMPLOYEE_ID HAVING COUNT(DEPARTMENT_ID) = 1 ); * 출처 https://leetcode.com/problems/primary-department-for-each-employee

Naver Blog

JAVA_LeetCode 1822_Sign of the Product of an Array

JAVA_LeetCode 1822_Sign of the Product of an Array 풀이 class Solution { public int arraySign(int[] nums) { // 음양수 여부에 맞춰 1 또는 -1을 곱해준다. int res = 1; for(int num : nums){ if(num == 0) return 0; res *= (num > 0 ? 1 : -1); } return res; } } * 출처 https://leetcode.com/problems/sign-of-the-product-of-an-array

Naver Blog

JAVA_LeetCode 2287_Rearrange Characters to Make Target String

JAVA_LeetCode 2287_Rearrange Characters to Make Target String 풀이 class Solution { public int rearrangeCharacters(String s, String target) { // 문자 배열을 만든 뒤, 각 문자 횟수를 세고 target 문자의 최소값을 도출한다. int[] arr1 = new int[26], arr2 = new int[26]; Arrays.fill(arr1, 0); Arrays.fill(arr2, 0); for(char ch : s.toCharArray()) arr1[ch - 'a']++; for(char ch : target.toCharArray()) arr2[ch - 'a']++; int cnt = Integer.MAX_VALUE; for(int i = 0; i < 26; i++){ if(arr2[i] != 0){ cnt = Math.min(cnt, arr1[i] / arr2[i]); }

Naver Blog

JAVA_LeetCode 2293_Min Max Game

JAVA_LeetCode 2293_Min Max Game 풀이 class Solution { public int minMaxGame(int[] nums) { // 인덱스 홀/짝수여부에 따라 최소/최대값을 구한다음 재귀형식으로 계속해서 반복한다. int len = nums.length, idx = 0; if(len == 1) return nums[0]; int[] arr = new int[len/2]; for(int i = 0; i < len; i += 2){ if(idx % 2 == 0) arr[idx++] = Math.min(nums[i], nums[i + 1]); else arr[idx++] = Math.max(nums[i], nums[i + 1]); } return minMaxGame(arr); } } * 출처 https://leetcode.com/problems/min-max-game

Naver Blog

JAVA_LeetCode 2299_Strong Password Checker II

JAVA_LeetCode 2299_Strong Password Checker II 풀이 class Solution { public boolean strongPasswordCheckerII(String password) { // 포함여부를 확인하여 반환한다. if(password.length() < 8) return false; String check = "!@#$%^&*()-+"; boolean bool1 = false, bool2 = false, bool3 = false, bool4 = false; for (char ch : password.toCharArray()) { if (Character.isLowerCase(ch)){ bool1 = true; }else if(Character.isUpperCase(ch)){ bool2 = true; }else if(Character.isDigit(ch)){ bool3 = true; }else if(check.indexOf(ch) != -1

Naver Blog

JAVA_LeetCode 2303_Calculate Amount Paid in Taxes

JAVA_LeetCode 2303_Calculate Amount Paid in Taxes 풀이 class Solution { public double calculateTax(int[][] brackets, int income) { // 이전 세금 등급과 현재 세금 등급의 상한을 확인 // 그 중 작은 값을 세율을 곱해서 세금에 더한다. // 기준 상한에서 이전 상한을 빼서 누적한다음, 현 세금 등급을 초기화한다. int prev = 0, num = 0; double res = 0; for(int[] bracket : brackets) { if(income <= 0) break; num = Math.min((bracket[0] - prev), income); res += (double)num * ((double)bracket[1] / 100); income -= num; prev = bracket[0]; } return res; } } * 출처 https://leetcode.com/p

Naver Blog

JAVA_LeetCode 2309_Greatest English Letter in Upper and Lower Case

JAVA_LeetCode 2309_Greatest English Letter in Upper and Lower Case 풀이 class Solution { public String greatestLetter(String s) { // 문자를 따로 추출하고, 알파벳 내림차순으로 대/소문자를 체크해서 존재할경우 반환한다. Set<Character> set = new HashSet<>(); for(char ch : s.toCharArray()) set.add(ch); for(char ch = 'Z'; ch >= 'A'; ch--){ if(set.contains(ch) && set.contains((char)('a' + (ch - 'A')))) return "" + ch; } return ""; } } * 출처 https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case

Naver Blog

JAVA_LeetCode 2315_Count Asterisks

JAVA_LeetCode 2315_Count Asterisks 풀이 class Solution { public int countAsterisks(String s) { // '|'가 짝수고 '*'이 존재하는만큼 개수를 체크한다. int num = 0, cnt = 0; for(int i = 0; i < s.length(); i++){ if(s.charAt(i) == '|') num++; else if(num % 2 == 0 && s.charAt(i) == '*') cnt++; } return cnt; } } * 출처 https://leetcode.com/problems/count-asterisks

Naver Blog

JAVA_LeetCode 2231_Largest Number After Digit Swaps by Parity

JAVA_LeetCode 2231_Largest Number After Digit Swaps by Parity 풀이 class Solution { public int largestInteger(int num) { // 좌측부터 큰 수의 동일한 패리티를 발견하여 서로 위치를 변경해준다. char temp; char[] ch = String.valueOf(num).toCharArray(); for(int i = 0; i < ch.length; i++){ for(int j = i + 1; j < ch.length; j++){ if(ch[j] > ch[i] && ((ch[j] % 2) == (ch[i] % 2))){ temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; } } } return Integer.parseInt(String.valueOf(ch)); } } * 출처 https://leetcode.com/problems/largest-number-after-d

Naver Blog

JAVA_LeetCode 2235_Add Two Integers

JAVA_LeetCode 2235_Add Two Integers 풀이 class Solution { public int sum(int num1, int num2) { // 더한 값을 반환한다. return num1 + num2; } } * 출처 https://leetcode.com/problems/add-two-integers

Naver Blog

JAVA_LeetCode 2236_Root Equals Sum of Children

JAVA_LeetCode 2236_Root Equals Sum of Children 풀이 class Solution { public boolean checkTree(TreeNode root) { // 루트 좌우 값을 더하여 루트 값과 비교한다. return root.val == root.right.val + root.left.val; } } * 출처 https://leetcode.com/problems/root-equals-sum-of-children

Naver Blog

JAVA_LeetCode 2239_Find Closest Number to Zero

JAVA_LeetCode 2239_Find Closest Number to Zero 풀이 class Solution { public int findClosestNumber(int[] nums) { // 정렬이후, 절대값을 비교하여 0에 가장 가까운 수를 체크한다.(만약 절대값이 같은 경우 양수를 사용한다.) int ans = Integer.MAX_VALUE; Arrays.sort(nums); for(int val : nums) { if(Math.abs(ans) >= Math.abs(val - 0)) ans = val; } return ans; } } * 출처 https://leetcode.com/problems/find-closest-number-to-zero

Naver Blog

JAVA_LeetCode 2243_Calculate Digit Sum of a String

JAVA_LeetCode 2243_Calculate Digit Sum of a String 풀이 class Solution { public String digitSum(String s, int k) { // 재귀함수를 통한 풀이법 if (s.length() <= k) return s; String str = ""; int len = 0, sum = 0; while (len < s.length()) { sum = 0; for (int i = 0; i < k && len + i < s.length(); i++) sum += s.charAt(len + i) - '0'; str += sum; len += k; } return digitSum(str, k); } } * 출처 https://leetcode.com/problems/calculate-digit-sum-of-a-string

Naver Blog

JAVA_LeetCode 2248_Intersection of Multiple Arrays

JAVA_LeetCode 2248_Intersection of Multiple Arrays 풀이 class Solution { public List<Integer> intersection(int[][] nums) { // 각 배열 요소별 특정 값 개수와 배열 수가 같은 경우 리스트에 담는다. List<Integer> list = new ArrayList<>(); int[] arr = new int[1001]; for(int[] num : nums){ for(int i : num) arr[i]++; } for(int i = 0; i < arr.length; i++){ if(arr[i] == nums.length) list.add(i); } return list; } } * 출처 https://leetcode.com/problems/intersection-of-multiple-arrays

Naver Blog

JAVA_LeetCode 2255_Count Prefixes of a Given String

JAVA_LeetCode 2255_Count Prefixes of a Given String 풀이 class Solution { public int countPrefixes(String[] words, String s) { // 문자열 배열에서 접두사인지 체크한다. int cnt = 0; for(int i = 0; i < words.length; i++){ if(s.startsWith(words[i])) cnt++; } return cnt; } } * 출처 https://leetcode.com/problems/count-prefixes-of-a-given-string

Naver Blog

JAVA_LeetCode 2259_Remove Digit From Number to Maximize Result

JAVA_LeetCode 2259_Remove Digit From Number to Maximize Result 풀이 class Solution { public String removeDigit(String number, char digit) { // 특정 숫자와 같을 때 반환값이 비어있거나, 해당 값과 차이가 0보다 큰 경우 해당 값을 리셋해준다. String res = "", num =""; for (int i = 0; i < number.length(); i++) { if (number.charAt(i) == digit){ num = number.substring(0, i) + number.substring(i + 1); if (res.isEmpty() || num.compareTo(res) > 0) res = num; } } return res; } } * 출처 https://leetcode.com/problems/remove-digit-from-number-to-maximi

Naver Blog

JAVA_LeetCode 2264_Largest 3-Same-Digit Number in String

JAVA_LeetCode 2264_Largest 3-Same-Digit Number in String 풀이 class Solution { public String largestGoodInteger(String num) { // 3자리 숫자 내림차순으로 비교하여 존재할경우 반환한다. String[] arr = {"999", "888", "777", "666", "555", "444", "333", "222", "111", "000"}; for(int i = 0; i < 10; i++) { if(num.contains(arr[i])) return arr[i]; } return ""; } } * 출처 https://leetcode.com/problems/largest-3-same-digit-number-in-string

Naver Blog

JAVA_LeetCode 2269_Find the K-Beauty of a Number

JAVA_LeetCode 2269_Find the K-Beauty of a Number 풀이 class Solution { public int divisorSubstrings(int num, int k) { // 약수를 찾을때 0이 아니고, 숫자를 해당 약수로 나눴을 때 0이 되면 반환값을 더해준다. int cnt = 0; String str = String.valueOf(num); for(int i = 0; i <= str.length() - k; i++){ if(Integer.parseInt(str.substring(i, k + i)) != 0 && (num % Integer.parseInt(str.substring(i, k + i)) == 0)) cnt++; } return cnt; } } * 출처 https://leetcode.com/problems/find-the-k-beauty-of-a-number

Naver Blog

JAVA_LeetCode 2273_Find Resultant Array After Removing Anagrams

JAVA_LeetCode 2273_Find Resultant Array After Removing Anagrams 풀이 class Solution { public List<String> removeAnagrams(String[] words) { // 문자열을 찾아서 정렬한다음, 중복된 문자가 아닌경우 리스트에 더한다. List<String> list = new ArrayList<>(); String str = "", temp = ""; for(int i = 0; i < words.length; i++){ char[] ch = words[i].toCharArray(); Arrays.sort(ch); temp = String.valueOf(ch); if(!str.equals(temp)){ list.add(words[i]); str = temp; } } return list; } } * 출처 https://leetcode.com/problems/find-resultant-array-aft

Naver Blog

JAVA_LeetCode 2278_Percentage of Letter in String

JAVA_LeetCode 2278_Percentage of Letter in String 풀이 class Solution { public int percentageLetter(String s, char letter) { // 문자 포함 여부를 세서 길이로 나눈다. int cnt = 0; for(int i = 0; i < s.length(); i++) cnt += s.charAt(i) == letter ? 1 : 0; return 100 * cnt / s.length(); } } * 출처 https://leetcode.com/problems/percentage-of-letter-in-string

Naver Blog

JAVA_LeetCode 2283_Check if Number Has Equal Digit Count and Digit Value

JAVA_LeetCode 2283_Check if Number Has Equal Digit Count and Digit Value 풀이 class Solution { public boolean digitCount(String num) { // 인덱스에 맞는 개수를 더한다음, 순차적으로 개수와 값이 동일한지 확인한다. int arr[] = new int[10]; for(char ch : num.toCharArray()) arr[ch - '0']++; for(int i = 0; i < num.length(); i++){ if(num.charAt(i) - '0' != arr[i]) return false; } return true; } } * 출처 https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value

Naver Blog

JAVA_LeetCode 2224_Minimum Number of Operations to Convert Time

JAVA_LeetCode 2224_Minimum Number of Operations to Convert Time 풀이 class Solution { public int convertTime(String current, String correct) { // 절대값으로 차이를 체크한 뒤, 60, 15, 5, 1로 나눈 수를 순차적으로 찾아서 더해준다. int[] prev = Arrays.stream(current.split(":")).mapToInt(Integer::parseInt).toArray(); int[] next = Arrays.stream(correct.split(":")).mapToInt(Integer::parseInt).toArray(); int time1 = prev[0] * 60 + prev[1], time2 = next[0] * 60 + next[1]; int res = 0, temp = 0; int target = time2 - time1; if(target <

Naver Blog

JAVA_LeetCode 1929_Concatenation of Array

JAVA_LeetCode 1929_Concatenation of Array 풀이 class Solution { public int[] getConcatenation(int[] nums) { // 배열을 2번 넣기 위해, 길이 2배의 배열을 만든 뒤 값을 초기화한다. int n = nums.length; int[] arr = new int[n * 2]; for(int i = 0; i< nums.length; i++){ arr[i] = nums[i]; arr[i + n] = nums[i]; } return arr; } } * 출처 https://leetcode.com/problems/concatenation-of-array

Naver Blog

JAVA_LeetCode 1935_Maximum Number of Words You Can Type

JAVA_LeetCode 1935_Maximum Number of Words You Can Type 풀이 class Solution { public int canBeTypedWords(String text, String brokenLetters) { // set을 이용, 중복 제거 문자를 담아 공백 기준 문자열 배열에서 해당 문자가 포함됬는지 체크한다. Set<Character> set = new HashSet<>(); int cnt = 0; String arr[] = text.split("\\s"); for(char ch : brokenLetters.toCharArray()) set.add(ch); for(String str : arr){ for(char ch : str.toCharArray()){ if(set.contains(ch)){ cnt++; break; } } } return arr.length - cnt; } } * 출처 https://leetcode.com/proble

Naver Blog

JAVA_LeetCode 1941_Check if All Characters Have Equal Number of Occurrences

JAVA_LeetCode 1941_Check if All Characters Have Equal Number of Occurrences 풀이 class Solution { public boolean areOccurrencesEqual(String s) { // map을 이용하여 문자 포함 개수를 넣은 뒤, set에 map의 value를 넣어서 길이가 1인지 확인하면 끝 HashMap<Character,Integer> map = new HashMap<>(); for(Character ch : s.toCharArray()) map.put(ch, map.getOrDefault(ch, 0) + 1); HashSet<Integer> set = new HashSet<>(map.values()); return set.size() == 1; } } * 출처 https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occu

Naver Blog

JAVA_LeetCode 1945_Sum of Digits of String After Convert

JAVA_LeetCode 1945_Sum of Digits of String After Convert 풀이 class Solution { public int getLucky(String s, int k) { // 각 문자별 매칭되는 수를 찾아서 수로 변환한 뒤 한자리마다 수를 더하면서 한자리 수가 될때까지 반복한다. String str = ""; int sum = 0; for(int i = 0; i < s.length(); i++) str += s.charAt(i) - 'a' + 1; while(k > 0){ sum = 0; for(int i = 0; i < str.length(); i++) sum += Character.getNumericValue(str.charAt(i)); str = sum + ""; k--; } return Integer.parseInt(str); } } Character의 getNumericValue()를 이용하여 숫자 문자를 숫자로 변환한다음 총합에 더한다

Naver Blog

JAVA_LeetCode 1952_Three Divisors

JAVA_LeetCode 1952_Three Divisors 풀이 class Solution { public boolean isThree(int n) { int cnt = 0; for(int i = 1; i <= n; i++){ if(n % i ==0) cnt++; } return cnt == 3; } } * 출처 https://leetcode.com/problems/three-divisors/

Naver Blog

JAVA_LeetCode 1957_Delete Characters to Make Fancy String

JAVA_LeetCode 1957_Delete Characters to Make Fancy String 풀이 class Solution { public String makeFancyString(String s) { int len = 0; // 현재 요소의 -1, -2 index에 해당하는 값을 확인, 만약 같은 문자가 있는 경우 추가하지 않는다. StringBuilder sb = new StringBuilder(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); len = sb.length(); if(len >= 2 && sb.charAt(len - 1) == c && sb.charAt(len - 2) == c) continue; sb.append(c); } return sb.toString(); } } * 출처 https://leetcode.com/problems/delete-characters-to-make-fancy-s

Naver Blog

JAVA_LeetCode 1961_Check If String Is a Prefix of Array

JAVA_LeetCode 1961_Check If String Is a Prefix of Array 풀이 class Solution { public boolean isPrefixString(String s, String[] words) { // 요소를 합치면서 같은지 확인 StringBuilder sb=new StringBuilder(); for (int i = 0; i < words.length; i++) { sb.append(words[i]); if (s.equals(sb.toString())) return true; } return false; } } * 출처 https://leetcode.com/problems/check-if-string-is-a-prefix-of-array

Naver Blog

JAVA_LeetCode 1967_Number of Strings That Appear as Substrings in Word

JAVA_LeetCode 1967_Number of Strings That Appear as Substrings in Word 풀이 class Solution { public int numOfStrings(String[] patterns, String word) { int cnt = 0; for(int i = 0; i < patterns.length; i++){ if(word.contains(patterns[i])) cnt++; } return cnt; } } * 출처 https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word

Naver Blog

JAVA_LeetCode 1971_Find if Path Exists in Graph

JAVA_LeetCode 1971_Find if Path Exists in Graph 풀이 class Solution { public void dfs(int idx, boolean[] b, List<List<Integer>> nodeList, List<Integer> list){ b[idx] = true; list.add(idx); for(int node : nodeList.get(idx)){ if(!b[node]) dfs(node, b, nodeList, list); } } public boolean validPath(int n, int[][] edges, int source, int destination) { boolean[] b = new boolean[n]; List<Integer> list = new ArrayList<>(); List<List<Integer>> nodeList = new ArrayList<>(); for (int i = 0; i < n; i++) nodeL

Naver Blog

JAVA_LeetCode 1859_Sorting the Sentence

JAVA_LeetCode 1859_Sorting the Sentence 풀이 class Solution { public String sortSentence(String s) { // 각 문자의 끝에 숫자가 있으며, 1~9까지의 수만 있으므로 문자열을 공백으로 나눠 각 문자별 숫자를 체크한다. String[] str = s.split(" "), words = new String[str.length]; int num = 0; for (String str2 : str) { num = str2.charAt(str2.length() - 1) - '0'; words[num - 1] = str2.substring(0, str2.length() - 1); } return String.join(" ", words); } } * 출처 https://leetcode.com/problems/sorting-the-sentence

Naver Blog

JAVA_LeetCode 1863_Sum of All Subset XOR Totals

JAVA_LeetCode 1863_Sum of All Subset XOR Totals 풀이 class Solution { public int subsetXORSum(int[] nums) { int res = 0; for (int num : nums) res |= num; return res * (1 << (nums.length - 1)); } } xor 합계의 합을 구하는 문제였는데, or 연산을 사용하여 푼 문제이다. or 연산 값과 or의 하위집합(2^(배열길이 - 1))을 곱해 값을 구한다. * 출처 https://leetcode.com/problems/sum-of-all-subset-xor-totals

Naver Blog

JAVA_LeetCode 1869_Longer Contiguous Segments of Ones than Zeros

JAVA_LeetCode 1869_Longer Contiguous Segments of Ones than Zeros 풀이 class Solution { public boolean checkZeroOnes(String s) { int num1 = 0, num2 = 0, max1 = 0, max2 = 0; // 1, 0에 맞춰서 연속 세그먼트를 계산한다. for (int i : s.toCharArray()) { if (i == '0'){ num1 = 0; if(++num2 > max1){ max1 = num2; } }else{ num2 = 0; if(++num1 > max2){ max2 = num1; } } } return max2 > max1; } } * 출처 https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros

Naver Blog

JAVA_LeetCode 1876_Substrings of Size Three with Distinct Characters

JAVA_LeetCode 1876_Substrings of Size Three with Distinct Characters 풀이 class Solution { public int countGoodSubstrings(String s) { int cnt = 0; // 3자리 문자열 중 각 문자가 다른경우를 체크한다. for(int i = 0; i < s.length() - 2; i++){ if( s.charAt(i) != s.charAt(i + 1) && s.charAt(i) != s.charAt(i + 2) && s.charAt(i + 1) != s.charAt(i + 2) ){ cnt++; } } return cnt; } } * 출처 https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters

Naver Blog

JAVA_LeetCode 1880_Check if Word Equals Summation of Two Words

JAVA_LeetCode 1880_Check if Word Equals Summation of Two Words 풀이 class Solution { public boolean isSumEqual(String firstWord, String secondWord, String targetWord) { int num1 = 0, num2 = 0, res = 0; // 각 word별 숫자를 계산할 때 문자열을 수로 맞추기 위해 n번 반복한 만큼의 n 자리 수를 더해준다. for(int i = 0; i < firstWord.length(); i++) num1 = num1 * 10 + firstWord.charAt(i) - 'a'; for(int i = 0; i < secondWord.length(); i++) num2 = num2 * 10 + secondWord.charAt(i) - 'a'; for(int i = 0; i < targetWord.length(); i++) res = res *

Naver Blog

JAVA_LeetCode 1886_Determine Whether Matrix Can Be Obtained By Rotation

JAVA_LeetCode 1886_Determine Whether Matrix Can Be Obtained By Rotation 풀이 class Solution { public boolean findRotation(int[][] mat, int[][] target) { int n = mat.length; // 배열의 deepEquals를 이용하여 90도 회전된 배열을 총 4번 비교한다. if (Arrays.deepEquals(mat, target)) return true; int[][] res = getRotatedArray(mat, n); if (Arrays.deepEquals(target, res)) return true; int[][] res2 = getRotatedArray(res, n); if (Arrays.deepEquals(target, res2)) return true; int[][] res3 = getRotatedArray(res2, n); return Arrays.

Naver Blog

JAVA_LeetCode 1893_Check if All the Integers in a Range Are Covered

JAVA_LeetCode 1893_Check if All the Integers in a Range Are Covered 풀이 class Solution { public boolean isCovered(int[][] ranges, int left, int right) { HashSet<Integer> set = new HashSet<>(); // 중복제거된 수를 set에 저장하여 left부터 right의 수 포함 여부를 체크한다. for(int i = 0; i < ranges.length; i++){ for(int j = ranges[i][0]; j <= ranges[i][1]; j++) set.add(j); } for(int i = left; i <= right; i++){ if(!set.contains(i)) return false; } return true; } } * 출처 https://leetcode.com/problems/check-if-all-the-integers-in

Naver Blog

JAVA_LeetCode 1897_Redistribute Characters to Make All Strings Equal

JAVA_LeetCode 1897_Redistribute Characters to Make All Strings Equal 풀이 class Solution { public boolean makeEqual(String[] words) { // 문자 빈도 체크, 문자열 길이와 비교한 나머지가 0이 아닌지 체크한다. int[] arr = new int[26]; for(String word : words){ for(char ch : word.toCharArray()){ arr[ch - 'a']++; } } for(int i = 0; i< 26; i++){ if(arr[i] % words.length != 0) return false; } return true; } } * 출처 https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal

Naver Blog

JAVA_LeetCode 1903_Largest Odd Number in String

JAVA_LeetCode 1903_Largest Odd Number in String 풀이 class Solution { public String largestOddNumber(String num) { // 홀수 판별을 위해 우측에서 좌측으로 홀수 체크, 존재 시 0부터 해당 위치까지 반환한다. for (int i = num.length() - 1; i >= 0; i--) { if (num.charAt(i) % 2 == 1) { return num.substring(0, i + 1); } } return ""; } } * 출처 https://leetcode.com/problems/largest-odd-number-in-string

Naver Blog

JAVA_LeetCode 1909_Remove One Element to Make the Array Strictly Increasing

JAVA_LeetCode 1909_Remove One Element to Make the Array Strictly Increasing 풀이 class Solution { public boolean canBeIncreasing(int[] nums) { int cnt = 0; // 현 요소값이 이전 요소값보다 작은 경우 2번째 이전 요소값과 비교한다. // 만약 같거나 크다면 이전 요소값을 초기화해준다. >> cnt가 2 이상이 된다. for (int i = 1; i < nums.length; i++) { if (nums[i] <= nums[i - 1]) { cnt++; if (i > 1 && nums[i] <= nums[i - 2]) { nums[i] = nums[i - 1]; } } } return cnt <= 1; } } * 출처 https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasi

Naver Blog

JAVA_LeetCode 1913_Maximum Product Difference Between Two Pairs

JAVA_LeetCode 1913_Maximum Product Difference Between Two Pairs 풀이 class Solution { public int maxProductDifference(int[] nums) { // 정렬 후 각 최저, 최고값 2개씩을 연산한다. Arrays.sort(nums); return nums[nums.length - 1] * nums[nums.length - 2] - nums[0] * nums[1]; } } * 출처 https://leetcode.com/problems/maximum-product-difference-between-two-pairs

Naver Blog

JAVA_LeetCode 1920_Build Array from Permutation

JAVA_LeetCode 1920_Build Array from Permutation 풀이 class Solution { public int[] buildArray(int[] nums) { // nums[nums[index]]를 반환하는 문제 int arr[] = new int[nums.length]; for (int i = 0; i < nums.length; i++) { arr[i] = nums[nums[i]]; } return arr; } } 처음엔 문제가 좀 이해안되는 문제였다. nums란 배열안에 nums의 값들을 인덱스로 찾아 반환하는 문제였다. * 출처 https://leetcode.com/problems/build-array-from-permutation

Naver Blog

JAVA_LeetCode 1925_Count Square Sum Triples

JAVA_LeetCode 1925_Count Square Sum Triples 풀이 class Solution { public int countTriples(int n) { // 1부터 n까지의 수의 한 쌍을 반복해서 제곱근을 찾아 값을 비교한다. int cnt = 0, sqrt = 0; for(int i = 1; i < n; i++){ for(int j = 1; j < n; j++){ sqrt = (int)Math.sqrt(i * i + j * j); if(sqrt <= n && sqrt * sqrt == i * i + j * j) cnt++; } } return cnt; } } * 출처 https://leetcode.com/problems/count-square-sum-triples

Naver Blog

JAVA_LeetCode 1791_Find Center of Star Graph

JAVA_LeetCode 1791_Find Center of Star Graph 풀이 class Solution { public int findCenter(int[][] edges) { // set을 통해 값을 비교해서 중복값을 찾는다. Set<Integer> set = new HashSet<>(); for(int i = 0; i < edges.length; i++){ for(int j = 0; j < edges[i].length; j++){ if(set.contains(edges[i][j])) return edges[i][j]; set.add(edges[i][j]); } } // 중복 값이 없으면 -1을 반환한다. return -1; } } * 출처 https://leetcode.com/problems/find-center-of-star-graph/

Naver Blog

JAVA_LeetCode 1796_Second Largest Digit in a String

JAVA_LeetCode 1796_Second Largest Digit in a String 풀이 class Solution { public int secondHighest(String s) { List<Integer> list = new ArrayList<>(); // 문자배열에서 중복 숫자를 제외한 숫자를 담는다. for(char ch : s.toCharArray()) { if(Character.isDigit(ch) && !list.contains(Integer.parseInt(String.valueOf(ch)))) { list.add(Integer.parseInt(String.valueOf(ch))); } } // 리스트를 정렬한다. Collections.sort(list); // 2개 이상인 경우 2번째로 큰 수를, 아닌 경우 -1을 반환한다. return list.size() > 1 ? list.get(list.size() - 2) : -1; } } * 출처 https://

Naver Blog

JAVA_LeetCode 1800_Maximum Ascending Subarray Sum

JAVA_LeetCode 1800_Maximum Ascending Subarray Sum 풀이 class Solution { public int maxAscendingSum(int[] nums) { // 1부터 반복하기 위해 0번째 요소값으로 초기화한다. int sum = nums[0], max = nums[0]; for(int i = 1; i < nums.length; i++){ // 작은 경우 합계를 초기화한다. if(nums[i] > nums[i - 1]) sum += nums[i]; else sum = nums[i]; max = Math.max(sum, max); } return max; } } * 출처 https://leetcode.com/problems/maximum-ascending-subarray-sum

Naver Blog

JAVA_LeetCode 1805_Number of Different Integers in a String

JAVA_LeetCode 1805_Number of Different Integers in a String 풀이 class Solution { public int numDifferentIntegers(String word) { // 문자열을 공백으로 변환 후 연속공백을 한 공백으로 기준을 나눠 배열화한다. String[] arr = word.replaceAll("[a-zA-Z]", " ").split("\\s+"); Set<String> set = new HashSet<String>(); // 숫자 문자열을 숫자로 변환한다음 set에 담아 중복을 제거한다. for (String str : arr) { if (!str.isEmpty()) set.add(String.valueOf(str.replaceAll("^0*", ""))); } return set.size(); } } * 출처 https://leetcode.com/problems/number-of-different-integers

Naver Blog

JAVA_LeetCode 1812_Determine Color of a Chessboard Square

JAVA_LeetCode 1812_Determine Color of a Chessboard Square 풀이 class Solution { public boolean squareIsWhite(String coordinates) { // 문자열의 각 문자를 더해서 2로 나눴을 때 0이면 true, 1이면 false를 반환 int num1 = coordinates.charAt(0) - 'a'; int num2 = coordinates.charAt(1); if ((num1 + num2) % 2 == 0) return true; return false; } } * 출처 https://leetcode.com/problems/determine-color-of-a-chessboard-square

Naver Blog

JAVA_LeetCode 1816_Truncate Sentence

JAVA_LeetCode 1816_Truncate Sentence 풀이 class Solution { public String truncateSentence(String s, int k) { // 공백으로 자른 문자배열의 0 ~ k까지 요소값을 합친다. return String.join(" ", Arrays.copyOfRange(s.split(" "), 0, k)); } } * 출처 https://leetcode.com/problems/truncate-sentence

Naver Blog

JAVA_LeetCode 1827_Minimum Operations to Make the Array Increasing

JAVA_LeetCode 1331_Rank Transform of an Array 풀이 class Solution { public int minOperations(int[] nums) { int cnt = 0, sum = 0; // 요소 차이만큼의 +1을 총합에 더해준다. for (int i = 0; i < nums.length - 1; i++) { if (nums[i] >= nums[i + 1]) { cnt = nums[i] - nums[i + 1] + 1; nums[i + 1] += cnt; sum += cnt; } } return sum; } } * 출처 https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing

Naver Blog

JAVA_LeetCode 1832_Check if the Sentence Is Pangram

JAVA_LeetCode 1832_Check if the Sentence Is Pangram 풀이 class Solution { public boolean checkIfPangram(String sentence) { if(sentence.length() < 26) return false; // set의 중복 제거방법을 이용하여 개수를 체크한다. HashSet<Character> set = new HashSet<>(); for(int i = 0; i < sentence.length(); i++) set.add(sentence.charAt(i)); return set.size() == 26; } } * 출처 https://leetcode.com/problems/check-if-the-sentence-is-pangram

Naver Blog

JAVA_LeetCode 1837_Sum of Digits in Base K

JAVA_LeetCode 1837_Sum of Digits in Base K 풀이 class Solution { public int sumBase(int n, int k) { int sum = 0; // n을 k진법에 맞춰 나눠서 나온 나머지를 더해준다. while(n > 0){ sum += (n % k); n = n / k; } return sum; } } * 출처 https://leetcode.com/problems/sum-of-digits-in-base-k

Naver Blog

JAVA_LeetCode 1844_Replace All Digits with Characters

JAVA_LeetCode 1844_Replace All Digits with Characters 풀이 class Solution { public String replaceDigits(String s) { // 문자열을 문자 배열화한다음 홀수 값만 반복해서 변환 후 문자열화한다. char[] ch = s.toCharArray(); for (int i = 1; i < ch.length; i += 2) ch[i] = (char)(ch[i - 1] + ch[i] - '0'); return new String(ch); } } * 출처 https://leetcode.com/problems/replace-all-digits-with-characters

Naver Blog

JAVA_LeetCode 1848_Minimum Distance to the Target Element

JAVA_LeetCode 1848_Minimum Distance to the Target Element 풀이 class Solution { public int getMinDistance(int[] nums, int target, int start) { int num = Integer.MAX_VALUE; // 숫자가 같은 값을 비교해서 가장 작은 수를 찾는다. for(int i = 0; i < nums.length; i++){ if (nums[i] == target) num = Math.min(Math.abs(i - start), num); } return num; } } * 출처 https://leetcode.com/problems/minimum-distance-to-the-target-element

Naver Blog

JAVA_LeetCode 1854_Maximum Population Year

JAVA_LeetCode 1854_Maximum Population Year 풀이 class Solution { public int maximumPopulation(int[][] logs) { // 년도(index), 횟수(value) 배열을 만들어서 최대횟수의 최소 인덱스를 출력한다. int[] cnt = new int[100]; int maxCnt = 0, year = 0; Arrays.fill(cnt, 0); for(int[] arr : logs){ for(int i = arr[0]; i < arr[1]; i++) cnt[(i - 1950)]++; } for(int i = 0; i < 100; i++){ if(cnt[i] > maxCnt){ maxCnt = cnt[i]; year = i + 1950; } } return year; } } * 출처 https://leetcode.com/problems/maximum-population-year

Naver Blog

JAVA_LeetCode 1742_Maximum Number of Balls in a Box

JAVA_LeetCode 1742_Maximum Number of Balls in a Box 풀이 class Solution { public int countBalls(int lowLimit, int highLimit) { int arr[] = new int[highLimit + 1]; int num = 0, sum = 0, max = Integer.MIN_VALUE; // 자릿수 합계 기준 값을 배열로 넣어준다. for(int i = lowLimit; i <= highLimit; i++) { num = i; sum = 0; while(num > 0){ sum = sum + num % 10; num = num / 10; } arr[sum]++; } // 가장 큰 값을 체크한다. for(int i = 0; i < arr.length; i++) { max = Math.max(max, arr[i]); } return max; } } * 출처 https://leetcode.com/probl

Naver Blog

JAVA_LeetCode 1748_Sum of Unique Elements

JAVA_LeetCode 1748_Sum of Unique Elements 풀이 class Solution { public int sumOfUnique(int[] nums) { // 값 : 키 map으로 선언한 후 횟수 초기화 HashMap<Integer,Integer> map = new HashMap<>(); int sum = 0; for(int i : nums) map.put(i, map.getOrDefault(i, 0) + 1); for(int i : map.keySet()){ if(map.getOrDefault(i, 0) == 1) sum += i; } return sum; } } * 출처 https://leetcode.com/problems/sum-of-unique-elements

Naver Blog

JAVA_LeetCode 1752_Check if Array Is Sorted and Rotated

JAVA_LeetCode 1752_Check if Array Is Sorted and Rotated 풀이 class Solution { public boolean check(int[] nums) { // 요소의 값이 인덱스 위치 + 1 의 요소 값보다 큰게 있을 경우 회전이 되지 않음 int cnt = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] > nums[(i + 1) % nums.length]) cnt++; } return cnt <= 1; } } * 출처 https://leetcode.com/problems/check-if-array-is-sorted-and-rotated

Naver Blog

JAVA_LeetCode 1758_Minimum Changes To Make Alternating Binary String

JAVA_LeetCode 1758_Minimum Changes To Make Alternating Binary String 풀이 class Solution { public int minOperations(String s) { // 각 짝/홀수인 경우 변경 시 값을 체크해준다. int chk = 0, chk2 = 0; for(int i = 0; i < s.length(); i++){ if(i % 2 == 0) chk += (s.charAt(i) == '0') ? 0 : 1; else chk += (s.charAt(i) == '1') ? 0 : 1; if(i % 2 == 0) chk2 += (s.charAt(i) == '1') ? 0 : 1; else chk2 += (s.charAt(i) == '0') ? 0 : 1; } return Math.min(chk, chk2); } } * 출처 https://leetcode.com/problems/minimum-changes-to-make-al

Naver Blog

JAVA_LeetCode 1768_Merge Strings Alternately

JAVA_LeetCode 1768_Merge Strings Alternately 풀이 class Solution { public String mergeAlternately(String word1, String word2) { // 가장 작은 길이만큼 반복해서 더해준뒤, 차감된 길이만큼 남은 문자를 더해준다. StringBuilder sb = new StringBuilder(); int len1 = word1.length(), len2 = word2.length(); int min = Math.min(len1, len2); for(int i = 0; i < min; i++){ sb.append(word1.charAt(i)); sb.append(word2.charAt(i)); } if(len1 > len2) sb.append(word1.substring(min, len1)); else if(len2 > len1) sb.append(word2.substring(min, len2)); re

Naver Blog

JAVA_LeetCode 1763_Longest Nice Substring

JAVA_LeetCode 1763_Longest Nice Substring 풀이 class Solution { public String longestNiceSubstring(String s) { // 문자열의 가장 긴 하위 문자열을 구한다. String res = ""; for(int i = 0; i < s.length(); i++){ for(int j = i + 1; j <= s.length(); j++){ if(niceChk(s.substring(i, j)) && s.substring(i, j).length() > res.length() ){ res = s.substring(i, j); } } } return res; } public boolean niceChk(String sub){ for(char ch = 'a'; ch <= 'z'; ch++){ char ch2 = Character.toUpperCase(ch); if( (sub.indexOf(ch) != -1 && sub.i

Naver Blog

JAVA_LeetCode 1773_Count Items Matching a Rule

JAVA_LeetCode 1773_Count Items Matching a Rule 풀이 class Solution { public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) { // 항목 값을 구한다. int idx = 0, res = 0; if(ruleKey.equals("color")) idx = 1; else if(ruleKey.equals("name")) idx = 2; // 항목값의 value가 일치하는 경우 출력값을 더해준다. for(int i = 0 ; i < items.size() ; i++){ if(items.get(i).get(idx).equals(ruleValue)) res++; } return res; } } * 출처 https://leetcode.com/problems/count-items-matching-a-rule

Naver Blog

JAVA_LeetCode 1779_Find Nearest Point That Has the Same X or Y Coordinate

JAVA_LeetCode 1779_Find Nearest Point That Has the Same X or Y Coordinate 풀이 class Solution { public int nearestValidPoint(int x, int y, int[][] points) { // x와 y중 하나라도 일치하는 경우 거리차이가 가장 작은 최소값을 구한다. // 없는 경우 -1을 반환한다. int min = Integer.MAX_VALUE, idx = -1, x2 = 0, y2 = 0, diff = 0; for(int i = 0; i < points.length; i++){ int[] point = points[i]; x2 = point[0]; y2 = point[1]; if(x == x2 || y == y2){ // 최소값중 가장 작은 인덱스를 찾는다. diff = Math.abs(x - x2) + Math.abs(y - y2); if(diff < min){ min = diff; id

Naver Blog

JAVA_LeetCode 1784_Check if Binary String Has at Most One Segment of Ones

JAVA_LeetCode 1784_Check if Binary String Has at Most One Segment of Ones 풀이 class Solution { public boolean checkOnesSegment(String s) { // 1의 앞에 0이 있으면 안된다. if(s.contains("01")) return false; return true; } } 문제 설명이 좀 이해가 안갔는데 1앞에 0이 있는지 확인하는 문제였다. 문자열에서 0앞에 1이 있으면 false를 반환한다. 1 앞에 0이 없을 경우 또는 1인 문자열인 경우 true를 반환한다. * 출처 https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones

Naver Blog

JAVA_LeetCode 1790_Check if One String Swap Can Make Strings Equal

JAVA_LeetCode 1790_Check if One String Swap Can Make Strings Equal 풀이 class Solution { public boolean areAlmostEqual(String s1, String s2) { // 문자열이 동일하거나, 문자 2개를 교환했을 때 동일한 경우 true이다. if(s1.equals(s2)) return true; List<Character> list1 = new ArrayList(), list2 = new ArrayList(); for(int i = 0; i < s1.length(); i++) { if(s1.charAt(i) != s2.charAt(i)) { list1.add(s1.charAt(i)); list2.add(s2.charAt(i)); } } // 모든 문자가 포함되지 않는지 확인 for(Character c : list1) { if(!(list2.contains(c))) return false; }

1 2 3 4 5 6 7 8 9 10