[TIL_Carrotww] 86 - 23/01/12

μœ ν˜•μ„Β·2023λ…„ 1μ›” 12일
0

TIL

λͺ©λ‘ 보기
101/138
post-thumbnail

πŸ“Carrotww의 μ½”λ”© 기둝μž₯

🧲 python algorithm interview

πŸ” Leetcode42 Trapping Rain Water hard

  • μŠ€νƒ 풀이
class Solution:
    def trap(self, height: List[int]) -> int:
        stack = []
        result = 0

        for i in range(len(height)):
            while stack and height[i] >= height[stack[-1]]:
                top = stack.pop()

                if not stack:
                    break
                distance = i - stack[-1] - 1
                waters = min(height[i], height[stack[-1]]) - height[top]

                result += distance * waters
            stack.append(i)

        return result
  • 투 포인트 λ°©μ‹μœΌλ‘œ ν‘ΈλŠ” 방법도 μžˆμ§€λ§Œ 이해가 잘 λ˜μ§€ μ•Šμ•„ λ‹€μ‹œ 풀어봐야겠닀.

🧲 C++

#include <bits/stdc++.h> λž€

μœ„ 헀더 νŒŒμΌμ€ λͺ¨λ“  λͺ¨λ“  ν‘œμ€€ 헀더 파일이 ν¬ν•¨λœ 헀더 νŒŒμΌμ΄λ‹€. μœ„ 헀더 파일 ν•œ 번만 μž‘μ„±ν•˜λ©΄ λͺ¨λ“  ν—€λ”νŒŒμΌμ„ μ‚¬μš©ν•  수 μžˆμ§€λ§Œ λ‹¨μ μœΌλ‘œλŠ” λΆˆν•„μš”ν•œ ν—€λ”νŒŒμΌλ„ μΆ”κ°€λ˜κΈ° λŒ€λ¬Έμ— 크기가 컀지고 컴파일 μ‹œκ°„μ΄ κΈΈμ–΄μ§„λ‹€λŠ” 단점이 μžˆλ‹€.

μš°λΆ„νˆ¬ μ•„λž˜ κ²½λ‘œμ— stdc++.h νŒŒμΌμ—μ„œ μ–΄λ–€ 헀더듀이 μžˆλŠ”μ§€ 확인할 수 μžˆλ‹€.
/usr/include/x86_64-linux-gnu/c++/7/bits
// C++

#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>

🧲 C++ algorithm

πŸ” λ°±μ€€ 10773번 제둜

#include <iostream>
#include <stack>
using namespace std;

int k, result = 0;
stack<int> stack_s;

int main(void) {
    ios::sync_with_stdio(0);
    cin.tie(0);

    cin >> k;
    while(k--) {
        int n;
        cin >> n;
        if(n == 0)
        stack_s.pop();
        else
        stack_s.push(n);
    }

    while(!stack_s.empty()) {
        result += stack_s.top();
        stack_s.pop();
    }
    cout << result;
}
profile
Carrot_hyeong

0개의 λŒ“κΈ€