목록코테/LeetCode (18)
공부기록
문제 https://leetcode.com/problems/course-schedule-ii/ 코드 import java.util.*; class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { List g[] = new List[numCourses]; int dp[] = new int[numCourses]; boolean visit[] = new boolean[numCourses]; List res = new ArrayList(); Queue q = new LinkedList(); for(int i=0; i
문제 https://leetcode.com/problems/search-a-2d-matrix-ii/ 코드 import java.util.*; class Solution { public boolean searchMatrix(int[][] matrix, int target) { int N = matrix.length; int M = matrix[0].length; int curRow = 0; int curCol = M-1; while(curCol >= 0 && curRow target) curCol--; else curRow++; } return false; } } 피드백 일단 예전에 풀었던 거지만 다시 못풀었다. (전에도 다시 못풀었음) 모범 답안은 오른쪽 끝에서 시작해서 현재 수가 target 보다 크면..
문제 https://leetcode.com/problems/unique-binary-search-trees/ 내 코드 import java.util.*; class Solution { int dp[]; public int numTrees(int n) { dp = new int[20]; for(int i=0; i
문제 https://leetcode.com/problems/valid-anagram/ 코드 import java.util.*; class Solution { public boolean isAnagram(String s, String t) { Map sm = new HashMap(); Map tm = new HashMap(); for(char c : s.toCharArray()){ if(sm.get(c) == null) sm.put(c, 0); sm.replace(c, sm.get(c)+1); } for(char c : t.toCharArray()){ if(tm.get(c) == null) tm.put(c, 0); tm.replace(c, tm.get(c)+1); } for(char key : sm.key..
문제 https://leetcode.com/problems/best-team-with-no-conflicts/ 내 코드 import java.util.*; class Solution { class Node implements Comparable{ int age; int score; public Node(int age, int score){ this.age = age; this.score = score; } @Override public int compareTo(Node obj){ if(this.score > obj.score) return 1; else if(this.score obj.age) return 1; else if(t..
문제 https://leetcode.com/problems/happy-number/ 내 코드 1차 코드 (시간복잡도 O(N), 공간복잡도 O(N)) import java.util.*; class Solution { public int makeSum(int n){ int tmp = n; int sum = 0; while(tmp != 0){ int rem = tmp%10; sum += (rem*rem); tmp/=10; } return sum; } public boolean isHappy(int n) { Set s = new HashSet(); int curNum = n; while(true){ if(s.contains(curNum)) break; s.add(curNum); curNum = makeSum(c..
문제 https://leetcode.com/problems/gas-station/ 코드 class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: if len(gas) == 1: if gas[0]-cost[0] < 0: return -1 else: return 0 left_gas = [0 for _ in range(len(gas))] presum = [0 for _ in range(len(gas)+1)] tot = 0 for i in range(len(gas)): left_gas[i] = gas[i]-cost[i] tot += left_gas[i] if tot < 0: return -1 for i in rang..
문제 https://leetcode.com/problems/interleaving-string/ 코드 class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: s1_len = len(s1) s2_len = len(s2) s3_len = len(s3) if s1_len + s2_len != s3_len: return False dp = [[True for _ in range(s1_len+1)] for _ in range(s2_len+1)] for i in range(1, s2_len+1): dp[i][0] = dp[i-1][0] and s2[i-1] == s3[i-1] for i in range(1, s1_len+1): dp[0]..