본문 바로가기

Problem Solving

(24)
[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/
[백준] 14499번: 주사위 굴리기 내가 짠 코드 #include #include #include using namespace std; // N * M 인 지도 //지도 좌표(r, c) r: 북쪽으로부터, c : 서쪽으로부터 /*r r r r rccccc */ //1 동쪽 2 서쪽 3 북쪽 4 남쪽 // 0,1 0,-1 -1,0 1,0 // -> dice_map(N); for(i=0;i
[백준] 14503번: 로봇 청소기 내가 짠 코드 #include #include #include #include using namespace std; // d가 0 1 2 3 북동남서 // 북 // 서 동 // 남 //현재방향 기준 왼쪽방향 /* 현재위치가 (r,c) 0(북) : 서쪽방향 (r,c-1) 3 후진 : r+1,c : 3 1(동) : 북쪽방향 (r-1,c) 0 후진 : r, c-1 : 0 2(남) : 동쪽방향 (r,c+1) 1 후진 : r-1,c : 1 3(서) : 남쪽방향 (r+1,c) 2 후친 : r, c+1 : 2 */ int N,M; int totalClean=0; int movement[4][3]={{0,-1,3},{-1,0,0},{0,1,1},{1,0,2}}; void step2(vector < vector < in..
[백준] 14891번: 톱니바퀴 내가 짠 코드 #include #include /* 톱니바퀴 저장 순서 0 7 1 6 2 5 3 4 맞닿는건 1-2번의 2,6 2-3번의 2,6 3-4번의 2,6 시계방향으로 돌면 : 1 70123456 반시계 : -1 12345670 */ using namespace std; int main(void){ int gear[4][8]; int move[4] = {0,}; int i,j,value; for(i=0;i=0;j--){ gear[i][j] = value%10; value = value/10; } } // for(i=0;i
[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