본문 바로가기

Problem Solving/리트코드

(7)
[LeetCode] Longest Word in Dictionary through DeletingSolution 중간중간 헷갈려서 조금 헤맸다. public안에 sort를 위한 bool을 추가했는데 앞에 static을 붙여야 돌아가더라. 왜 붙여야 하는지는 아직 이해 못함. 내가 짠 코드 class Solution { public: static bool sortWithLength(string a, string b){ return a.length()>b.length(); } string findLongestWord(string s, vector& d) { string ans; int ans_len=0; sort(d.begin(),d.end(),sortWithLength); int i,j,dPos,sPos; for(i=0;i
[LeetCode] Arithmetic SlicesSolution 내가 짠 코드 class Solution { public: int numberOfArithmeticSlices(vector& A) { if(A.size()
[LeetCode] Linked List Cycle 리트코드 하기 전에는 몰랐던 링크드 리스트 나오면 꼭 생각해야하는 fast/slow (runner/walker) 방식. 알아두면 유용. 내가 짠 코드 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { ListNode *walker, *runner; walker = head; runner = head; while(runner!=NULL && runner->next!=NULL){ walker = walker->..
[LeetCode] Number of 1 Bits 비트연산해서 1이 몇 개 있는지 판별하는 코드. 한 번 풀어놓으면 유용하다. 자주 나오지는 않지만 비트연산 나오면 알고 있으면 유용하게 쓰인다고 생각. 비트연산이 잘 안나와 나오기만 하면 죄다 낯설어서 그렇지... 내가 짠 코드 class Solution { public: int hammingWeight(uint32_t n) { int count =0; for(int i=0;i> 1; } return count; } }; leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3625/
[LeetCode] Squares of a Sorted Array vector sort하는 법. sort(벡터이름.begin(), 벡터이름.end()); 나는 단순히 제곱 해준 후 sort 쓰는 법 생각했는데 most votes에서는 sort안쓰고, 제곱 후 left most, right most 사용해서 비교하면서 새 vector 만들어서 값 넣어줬다. sort쓸 때의 속도가 input이 많을 때 직접 비교하는 알고리즘 보다 더 빠를지 느릴지 모르겠다. 내가 짠 코드 class Solution { public: vector sortedSquares(vector& nums) { int i; for(i=0;i= 0; k--) { if (abs(A[r]) > abs(A[l])) res[k] = A[r] * A[r--]; else res[k] = A[l] * A[l++]; ..
[LeetCode] 541. Reverse String II 디스커스 중에 min이용해서 끝 값이랑, 현재위치 + k 값하는 게 있었는데, 그렇게 하면 내가 짠 코드의 if, else를 한 개로 합칠 수 있을 듯 하다. 내가 짠 코드 class Solution { public: string reverseStr(string s, int k) { int i=0,j; char tmp; while(i
[LeetCode] 344. Reverse String 처음 돌렸을때는 16ms나왔는데 계속 돌릴수록 다른 Discuss 답안이랑 비슷한 28-32ms 나온다. 간단한 구조여서 어떻게 짜든 다 비슷하게 나오는듯. 내가 짠 코드 class Solution { public: void reverseString(vector& s) { char tmp; for(int i=0;i