본문 바로가기

Algorithm101

[LeetCode] 226 | Invert Binary Tree 226 | Invert Binary Tree https://leetcode.com/problems/invert-binary-tree/ 이상 코드 재귀함수를 이용한 풀이 class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if root: root.left, root.right = \ self.invertTree(root.right), self.invertTree(root.left) return root return None 재귀 함수로 작성 root.right 를 인자를 넘겼기 때문에 맨 오른쪽의 리프 노드부터 스왑이 이루어짐 가장 말단, 리프 노드까지 내려가서 백트래킹하면서 스왑하는 상향 (Bottom-Up) 방식 BFS를 이용한 풀이 c.. 2022. 5. 30.
[LeetCode] 191 | Number of 1 Bits 191 | Number of 1 Bits https://leetcode.com/problems/number-of-1-bits/ 작성 코드 접근 방법 string 형으로 변환 후 1을 count class Solution: def hammingWeight(self, n: int) -> int: return(bin(n).count("1")) str(n)으로 설정하니 00000000000000000000000000001011 -> 11 으로 변환되었음,n 자체는 10진수 bin() 함수를 이용하여 10진수를 2진수로 변환 추가 코드 비트 연산을 이용한 정석적인 풀이 class Solution { public: int hammingWeight(uint32_t n) { int count = 0; while (n .. 2022. 5. 24.
[BOJ] 1629 | 곱셈 1629 | 곱셈 https://www.acmicpc.net/problem/1629 작성 코드 #include using namespace std; int main() { unsigned long long a, b, c; cin >> a >> b >> c; unsigned long long res = 1; for(unsigned long long i = 0 ; i a >> b >> c; int res = 1; if ((c % 2 == 1) & (b % 2 == 1)) { res = a % c; } else { res = a * a % c; } cout 몇 개는 맞지만 몇 개는 오답이었음 이상 코드 #include using nam.. 2022. 5. 23.
[LeetCode] 1523 | Count Odd Numbers in an Interval Range 1523 | Count Odd Numbers in an Interval Range https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/ 작성 코드 class Solution { public: int countOdds(int low, int high) { int end; end = (low % 2 == 1) + (high % 2 == 1); if (end == 0) { return (high - low) / 2; } else if (end == 1) { return (high - low + 1) / 2; } else { return (high - low + 2) / 2; } } }; 이상 코드 class Solution { public.. 2022. 5. 19.
[BOJ] 17466 | N! mod P (1) 17466 | N! mod P (1) https://www.acmicpc.net/problem/17466 작성 코드 #include using namespace std; int main(){ int n, p; cin >> n >> p; int fac = 1; for (int i = 1 ; i n >> p ; unsigned long long res = 1; for (unsigned long long i = 1 ; i 2022. 5. 17.
[트리] 정렬된 배열의 이진 탐색 트리 반환 108 | Convert Sorted Array to Binary Search Tree https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 작성 코드 (30분 내 해결 X) 인덱스 값으로 append? 재귀 호출?? 어떻게 인자를 받을 것인가? 이상 코드 from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sortedArrayToBST(self, nums: List[int]) ->.. 2022. 5. 16.
반응형