8월, 2021의 게시물 표시

Leetcode 25h August

Leetcode 25h August Sum of Square Numbers 이 문제는 a 2 + b 2 = c 가 존재하는지 체크 하는 로직입니다. This problem is checking whether has a condition values like a formula that a 2 + b 2 = c 이경우 저는 c - a 2 값을 저장한 DP 리스트를 만들고, for 문을 돌면서 math.sqrt가 정수인 값을 찾도록 있을 경우 True 없을 경우 False를 리턴하는 방식을 사용했습니다. in this case, i create one list named DP, in theirs they saved c - a 2 value until a * a <= c after that loop the dp and checking whether the square root of element is integer value or not Python class Solution : def judgeSquareSum ( self , c : int ) - > bool : dp = [ ] i = 0 j = 0 while i * i <= c : dp . append ( c - i * i ) i += 1 for x in dp : if math . sqrt ( x ) % 1 == 0 : return True return False

Leetcode 24h August

Leetcode 24h August Complex Number Multiplication 이 문제는 두개의 String 값이 주워졌을 경우, 파싱을 통해 실수와 허수 나누고 그것에 대한 곱을 계산해서 리턴하는 문제입니다. This is the problem when they given two string value then return value that product of two imaginary numbers after parsed 이경우는 단순히 String parsing 이기 때문에 딱히 방법없이 split 메소드를 사용해서 값 가져오고, 그 후에 계산해서 리턴하였습니다. in this case, i don’t need to a specific way, i just used split method given default by language, and then return calculated value from parsed data. Java class Solution { public String complexNumberMultiply ( String num1 , String num2 ) { String [ ] arrOfNum1 = num1 . split ( "\\+" ) ; String [ ] arrOfNum2 = num2 . split ( "\\+" ) ; int x = Integer . parseInt ( arrOfNum1 [ 0 ] ) ; int y = Integer . parseInt ( arrOfNum2 [ 0 ] ) ; System . out . printf ( "%d %d \n" , x , y ) ; int xi = Integer . parseInt ( arrOfNum1 [ 1 ] . split (...

Leetcode 23th August

Leetcode 23th August Two Sum IV - Input is a BST 이 문제는 Tree에서 두개를 선택해서 합이 K가 되는 경우의수가 존재하는지 확인하는 문제입니다. This problem is checking condition that when you choose the two element in tree the sum of the elements value are same as K 이경우 저는 일단 Tree을 순회하면서 값을 List에 추가한 후에 이중 for loop를 통해 두개의 합이 k가 되는 값이 있는지 체크 하는 방법을 사용했습니다. for this case, first of all i gathering a every elements value in tree use dfs algorithm, then try to found a has a case that the sum of two elements is same as k Java /** * 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 boolean findTarget ( TreeNode root , int k ) { List < Integer > list ...

Leetcode 21th August

Leetcode 21th August Sudoku Solver 이 문제는 9x9 배열의 sudoku 문제 주워지고 그 빈값에 알맞은 답을 적용하는 방식입니다. This is the problem that return matrix that set correct value 이 경우에도 저는 grid 한 방식으로 9X9 배열을 돌면서 값이 없을 경우 1~9까지의 숫자를 돌면서 해당 답이 valid 할 경우 다음 row, col에 값을 대입하는 형태로 문제를 풀었습니다. i use previous way for solving this problem, so looping matrix then if the value is empty, i found a correct value from 1 ~9 Python class Solution : N = 9 def is_valid ( self , board , row , col , num ) : """ This function is for checking this board is valid or not :return: boolean """ # TODO: checking row is valid for x in range ( 9 ) : if board [ row ] [ x ] == num : return False # TODO: chcking colum in valid for x in range ( 9 ) : if board [ x ] [ col ] == num : return False # TODO: checking box is valid ...

Leetcode 20th August

Leetcode 20th August Valid Sudoku 이 문제는 제공된 9x9 matrix sudoku 문제가 valid 한지 안한지 리턴하는 문제 입니다. This is the problem to check whether given matrix is valid or not 이 경우는 간단히 O(N^2) 을 써서 사용했습니다. valid 한 조건의 경우 row, col, box에 같은 변수값이 있는지 없는지로 추가하였습니다. for solving problem i use that way that is looping given matrix and if the value is exists checking that value is valid or not. if the result is invalid then return False. and if don’t found a any invalid value in loop matrix then return True. Python class Solution : def is_valid ( self , board , row , col , num ) : """ This is the function to checking given num is valid or not. return: boolean """ # TODO: checking row is valid for x in range ( 9 ) : if x != col and board [ row ] [ x ] == num : return False # TODO: chcking colum in valid for x in range ( 9 ) : if x ...

Leetcode 17th August

Leetcode 17th August Leetcode 17th August Count Good Nodes in Binary Tree 이 문제는 Tree 를 순회하면서 Node의 상태가 good인 node의 갯수를 리턴하는 문제입니다. This is the Question return count of good node in tree 상태가 good 인 node란? tree의 parent의 값 들이 모두 자기 자신보다 작거나 같은 경우 What is the meaning of good node? the node’s value are greater than or equal to all of the values of parent node in tree 그래서 저는 dfs를 통해 Tree를 순회하면서 node의 parent의 값을 비교하는 방식으로 구현하였습니다. So i use dfs algorithm for access node by tree, and then calculate this node is good or not. if the node is good node then i adding 1 in answer Python # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution : def goodNodes ( self , root : TreeNode ) - > int : queue = deque ( ) root . parent = None queue . append ( root ) ...

Leetcode 15th August

Leetcode 15th August Leetcode 15th August Set Matrix Zeroes 이 문제는 matrix 가 주워졌을때 cell 중에 0 이포함되어있으면 그 해당 rows, cols의 값을 0으로 변경하는 문제 입니다. This question is Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0’s, and return the matrix. 그래서 저의 경우 rows, cols sets를 만든 다음에 matrix[i][j] 값이 0 일 경우 rows 에 i, cols에 j를 추가하고, 그담에 loop를 통해서 i가 rows 에 포함되어있거나 cols 가 j에 포함되어있을 경우 값을 0으로 변경하는 방식으로 해결했습니다. For solving this problem i create two sets named rows , cols and add i in rows and j in cols if the cell value is 0, after set up rows, cols values, set matrix value 0 if i value in rows or j value in cols Python Time complexity: O(M * N) class Solution : def setZeroes ( self , matrix : List [ List [ int ] ] ) - > None : """ Do not return anything, modify matrix in-place instead. """ n = len ( matrix ) m = len ( matrix [ 0 ] ) res = ...

Leetcode 14th August

Leetcode 14th August Group Anagrams 이 문제는 anagrams 가 같은 문자들 끼리 그룹화 해서 보여주는 문제 This question is return string list group by same anagrams 그래서 단순하게 저의 경우는 정렬 된 문자를 키로 가지는 map 만들고, 후에 값만 리턴 하는방식으로 문제를 해결하였습니다. For solving this problem, i used make a Map, that is key, value store, then the key is sorted string, and value is string list, after generate map i return values. Python class Solution : def groupAnagrams ( self , strs : List [ str ] ) - > List [ List [ str ] ] : res = defaultdict ( list ) for s in strs : ss = "" . join ( sorted ( s ) ) res [ ss ] . append ( s ) return [ v for i , v in res . items ( ) ] 요새 자바도 연습하고 있어서 똑같은 방식으로 자바 코드로도 한번 짜봤습니다. i also try to write a code in java, because for now i learning Java Java class Solution { public List < List < String >> groupAnagrams ( String [ ] strs ) { Map < String , List < String >> map = n...