목록Study/Algorithm (400)
hwooo
https://leetcode.com/problems/validate-binary-search-tree/description/풀이코드 1 : 주어진 트리를 중위순회하며 순서대로 저장 후 이를 탐색하여 올바른 트리인지 확인 시간이 느려서 다른 사람들의 풀이를 보고 다시 풀었다.코드 2 : 순회하며 현재 노드에서의 최대, 최소값 범위를 정해서 해당 범위에서 벗어나면 false를 반환코드 1class Solution {private: vector nodes;public: bool isValidBST(TreeNode* root) { // 주어진 트리 중위 순회 inOrder(root); int size = nodes.size(); for (i..
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/풀이답을 떠올리지 못해 답지를 봤고, 그리디 방식으로 코드를 구성했다.코드class Solution {public: int maxProfit(vector& prices) { int buy = prices[0], size = prices.size(); int maxProfit = 0; // 이전 인덱스에서 주식을 사고, 파는 게 이득인 경우에 무조건 판매 for (int i = 1; i
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/풀이카데인 알고리즘을 사용, 배열을 한 번만 순회하면서 최대 이익을 구한다.코드class Solution {public: int maxProfit(vector& prices) { int buy = prices[0], profit = 0; for (int i = 1; i
https://leetcode.com/problems/search-in-rotated-sorted-array/ 풀이배열의 시작지점을 이분탐색으로 찾고, target 값과 비교해 배열의 새로운 시작과 끝 지점을 정한다.새로 만든 배열의 범위에서 target을 찾는다코드class Solution {public: int search(vector& nums, int target) { int start, end, minIdx; start = 0, end = nums.size() - 1; // 시작 지점 찾기 while (start nums[end]) start = mid + 1; e..
https://leetcode.com/problems/reach-a-number/description/ 풀이dp라 생각했는데 도저히 답이 나오지 않아 풀이를 봤다.그 중 이 분의 설명이 가장 이해가 되어서 올려두었다. 코드class Solution {public: int reachNumber(int target) { if (target
https://leetcode.com/problems/simplify-path/submissions/풀이"/"를 기준으로 디렉토리를 나눠 deque에 저장했다. 저장할 때는 앞으로 넣어 ".."이 나오면 앞에서 최신 디렉토리를 제거했다.최종 경로를 만들 때에는 뒤에서부터 탐색해 원래 순서를 맞춰주었다.코드class Solution {public: string simplifyPath(string path) { deque directories; int idx = 0, len = path.length(); while(idx
https://school.programmers.co.kr/learn/courses/30/lessons/131704 프로그래머스코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.programmers.co.kr풀이스택을 사용하여 컨테이너의 박스들을 확인했다.주컨테이너는 한 번 박스를 빼면 다시 넣지 못하는 점에 유의해야 한다.코드#include using namespace std;int solution(vector order) { stack primary, secondary; int ans = 0; for (int i = order.size(); i >= 1; i--) ..
https://leetcode.com/problems/course-schedule/풀이위상정렬을 사용한 문제.코드class Solution {public: bool canFinish(int numCourses, vector>& prerequisites) { vector seq[2000]; int inDegree[2000] = {0, }; queue q; // 노드의 레벨과 before-now 정보 저장 for (int i = 0; i return false for (int i = 0; i