Leetcode 공부 - Valid Anagram

LeetCode(242) - Valid Anagram 문제 문자열 s와 t가 주어진다. 두 문자열이 Anagram인지 판단하여 Anagram이면 true를, 아니라면 false를 반환하라. 입력 Input: s = "anagram", t = "nagaram" 출력 Output: true 풀이 s와 t를 정렬하고, 문자열만큼의 길이를 순회하면서 해당 index에 s와 t가 다르다면 false를 반환한다. 문자열 순회가 끝나면 true를 반환한다. 코드 #include<iostream> #include<algorithm> using namespace std; bool isAnagram(string s, string t) { if (s.size() == 0 || t.size() == 0) return false; if (s....

January 14, 2023 · 2 min · 229 words · Me

Leetcode 공부 - Container Duplicate

LeetCode(217) - Contains Duplicate 문제 정수 배열 nums가 주어진다. 중복된 정수가 배열에 있다면 true를 반환하고 중복이 없다면 false를 반환하라 입력 Input: nums = [1,1,1,3,3,4,3,2,4,2] 출력 Output: true 풀이 배열을 순회하면서 각 값들을 set에 넣는다. set에 현재 배열의 값과 동일한 값이 있다면 중복이므로 true를 반환한다. 배열을 모두 순회했다면 중복이 없으므로 false를 반환한다. 코드 bool containsDuplicate(vector<int>& nums) { unordered_set<int> uset; for(int num : nums) { if(uset.count(num) > 0) { return true; } uset....

January 13, 2023 · 1 min · 75 words · Me

Leetcode 공부 - Majority Element

LeetCode(169) - Majority Element 문제 n의 길이를 가지는 정수형 배열 nums가 주어진다. nums에 저장된 정수 중 가장 많은 빈도의 정수를 반환하라. 가장 많은 빈도를 갖는 정수는 2/n개 이상이다. 입력 nums = [2,2,1,1,1,2,2] 출력 Output: 2 풀이 key는 정수 값을, value는 정수의 빈도를 나타내는 unordered_map을 사용한다. nums를 순회하면서, 해당 정수의 key를 조회, value의 값을 +1 하여 빈도를 나타낸다. 빈도가 2/n이상이라면 해당 정수가 가장 많은 빈도의 정수이므로, 해당 정수를 반환한다. 코드 class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int, int> umap; int maxSize = nums....

January 10, 2023 · 1 min · 108 words · Me

LeetCode 공부 - Intersection of Two Linked Lists

LeetCode(160) - Intersection of Two Linked Lists 문제 두 Linked List의 headA, headB가 주어진다. 두 List 가 만나는 교차점이 있다면 해당 노드를 반환하고, 두 리스트가 교차하지 않고 평행하다면 null을 반환하라. 입력 Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 skipA, skipB는 주어지는 값이 아닌 설명을 위한 예시이다. 출력 Output: Intersected at '8' 풀이 문제 - Linked List Cycle 와 매우 유사하다. unordered_set을 이용해 ListNode의 고유성을 기준으로 교차점이 있는지 판단한다....

January 10, 2023 · 1 min · 148 words · Me

LeetCode 공부 - Linked List Cycle

LeetCode(141) - Linked List Cycle 문제 Linked List의 head가 주어진다. 주어진 Linked List가 cycle을 갖는지 판단하라. 입력 head = [3,2,0,-4], pos = 1 pos는 주어지는 값이 아니고 설명을 돕기위한 예시입니다.. 출력 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). 풀이 ListNode의 포인터는 유니크하므로, 해당 포인터를 set으로 관리하여 중복을 확인한다. ListNode 타입의 unordered_set을 만든다. unordered_set에 현재 ListNode의 포인터가 없다면 현재 노드를 set에 삽입한다....

January 10, 2023 · 1 min · 127 words · Me