본문 바로가기

Problem solving/LeetCode22

[LeetCode] 2360. Longest Cycle in a Graph (C++) 문제 방향이 있는 그래프가 주어질 때, 각 노드는 최대 한 개의 나가는 방향의 엣지를 가진다. 엣지들의 길이가 주어졌을 때 길이가 가장 긴 사이클을 구하기. 엣지가 없는경우는 -1의 값을 가진다. 사이클이 없는 경우에는 -1를 리턴 생각할 것 출발 지점과 도착지점이 같은 경우가 사이클에 해당 DFS를 사용해 위 조건을 만족했을 때를 찾기 코드 class Solution { public: int answer = -1; void dfs(int start, int next, int len, vector visited, vector edges){ visited[next] = true; if(start == next) { answer = max(answer, len); } if(edges[next] != -1){.. 2023. 7. 11.
[LeetCode] 34. Find First and Last Position of Element in Sorted Array (C++) 문제 오름차순으로 정렬된 정수 배열이 주어질 때 target의 시작과 끝을 찾기 시간복잡도 O(log n) 생각할 것 target 숫자 중 가장 작은 인덱스를 찾는 함수 만들기 target + 1 숫자에서 인덱스를 하나 뺀 값이 end에 해당 코드 class Solution { public: int findLowerBound(vector& nums, int target) { int start = 0, end = nums.size() - 1; while(start 2023. 7. 4.
[LeetCode] 33. Search in Rotated Sorted Array (C++) 문제 중복없이 오름차순으로 정렬된 정수 배열이 회전되어 있다. target의 인덱스를 찾아라 O(log n)의 시간복잡도를 갖도록 하기 생각할 것 O(log n)의 시간복잡도를 갖기위해 이진 탐색을 이용하기 중간값과 양쪽 끝값 비교하기 코드 class Solution { public: int search(vector& nums, int target) { int start = 0; int end = nums.size() - 1; int mid; while(start 2023. 7. 4.
[LeetCode] 28. Find the Index of the First Occurrence in a String (C++) 문제 needle과 haystack 두 개의 문자열이 주어졌을 때, haystack에서 가장 처음 나타난 needle의 인덱스 찾기. 없으면 -1을 리턴 생각할 것 string의 find를 이용하면 되지 않을까? 💡 string의 find함수 문자열을 찾으면 해당 문자열의 시작 인덱스를 리턴 찾지못한다면 -1을 리턴 코드 class Solution { public: int strStr(string haystack, string needle) { return haystack.find(needle); } }; 2023. 7. 3.