File tree Expand file tree Collapse file tree 2 files changed +81
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 2 files changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ 풀이 :
3+ 현재의 price에 도달하기 전 가장 작은 price를 min_cur로 업데이트
4+ price - min_cur가 저장되있는 max_profit보다 크면 값을 업데이트
5+
6+ prices의 개수 N
7+
8+ TC : O(N)
9+
10+ SC : O(1)
11+ */
12+
13+
14+ #include < vector>
15+ using namespace std ;
16+
17+ class Solution {
18+ public:
19+ int maxProfit (vector<int >& prices) {
20+ int min_cur = prices[0 ];
21+ int max_profit = 0 ;
22+
23+ for (int & price : prices)
24+ {
25+ if (price < min_cur)
26+ {
27+ min_cur = price;
28+ continue ;
29+ }
30+
31+ int profit = price - min_cur;
32+ if (profit > max_profit)
33+ max_profit = profit;
34+ }
35+ return max_profit;
36+ }
37+ };
Original file line number Diff line number Diff line change 1+ /*
2+ 풀이 :
3+ strs의 각 str에 대해 정렬을 통해 아나그램을 동일한 판별할 수 있도록 하고
4+ 해시테이블 unordered_map에 ans 중 어느 인덱스에 속하는 아나그램인지 판별하도록 한다
5+
6+ 이전에 저장되지 않은 아나그램일 경우 새로운 vector<string>을 ans에 추가하고
7+ unordered_map에 추가해준다
8+
9+ strs의 개수 N, 평균 길이 L
10+
11+ TC : O(N * L log(L))
12+ strs의 개수(N)만큼 반복문을 실시하고 sort는 L log(L)의 시간복잡도를 가져서
13+
14+ SC : O(N * L)
15+ 해시테이블 lookup의 크기는 최대 개수 * 평균길이 만큼 할당될 수 있으므로 (다 안겹칠 경우우)
16+ */
17+
18+ #include < vector>
19+ #include < string>
20+ using namespace std ;
21+
22+ class Solution {
23+ public:
24+ vector<vector<string>> groupAnagrams (vector<string>& strs) {
25+ int index = 0 ;
26+ unordered_map<string, int > lookup;
27+ vector<vector<string>> ans;
28+
29+ for (string& str : strs)
30+ {
31+ string sorted = str;
32+ sort (sorted.begin (), sorted.end ());
33+ if (lookup.count (sorted))
34+ ans[lookup[sorted]].push_back (str);
35+ else
36+ {
37+ lookup[sorted] = index;
38+ index++;
39+ ans.push_back (vector<string>{str});
40+ }
41+ }
42+ return ans;
43+ }
44+ };
You can’t perform that action at this time.
0 commit comments