본문 바로가기

알고리즘 문제풀이/leetcode142

[leetcode 234] Palindrome Linked List Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true Follow up: Could you do it in O(n) time and O(1) space? 문제 풀이: 첨에 follow up을 무시하고 풀었다. 어떻게 거꾸로 돌지?해서 무시함 ㅇㅇ 첫 번째 방법(c++): 연결리스트를 모두 벡터에 집어넣고 전체 길이가 홀수/짝수일때를 나눠서 가운데부터 비교한다. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *n.. 2020. 10. 31.
[leetcode 226] Invert Binary Tree Invert a binary tree. Example: Input: Output: 문제 풀이: - 재귀...난이도는 쉬움인데 해도 해도 모르겠다 재귀는 - 현재 노드에서 왼쪽 서브트리와 오른쪽 서브트리를 바꾸는 것이 중점 - 왼쪽 서브트리와 오른쪽 서브트리를 새로 만들어서 붙인다. class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root == nullptr){ return root; } TreeNode* right = invertTree(root->right); TreeNode* left = invertTree(root->left); root->left = right; root->right = left; return root; } }; 2020. 10. 30.
[leetcode 49] Group Anagrams Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Example 2: Input: strs = [""] O.. 2020. 10. 30.
[leetcode 56] Merge Intervals Given a collection of intervals, merge all overlapping intervals. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. NOTE: input types have been changed o.. 2020. 10. 30.