Skip to content

[haung921209] WEEK 02 solutions #1248

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Apr 17, 2025
67 changes: 67 additions & 0 deletions 3sum/haung921209.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
```cpp
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
set<vector<int>> res;
for(int i=0;i<nums.size();i++){
int l = i+1, r = nums.size()-1;

while(l<r){
int sum = nums[i]+nums[l]+nums[r];

if(sum<0){
l++;
}else if(sum>0){
r--;
}else{
res.insert({nums[i], nums[l], nums[r]});
l++;
r--;
}
}
}

return vector<vector<int>>(res.begin(), res.end());
}
};
```

- set -> vector 사용 이유는 중복 제거를 위함

```cpp
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
set<vector<int>> res;
for(int i=0;i<nums.size();i++){
if(i != 0 && nums[i] == nums[i-1]) continue;

int l = i+1, r = nums.size()-1;

while(l<r){
int sum = nums[i]+nums[l]+nums[r];

if(sum<0){
l++;
}else if(sum>0){
r--;
}else{
res.insert({nums[i], nums[l], nums[r]});
l++;
r--;
}
}
}

return vector<vector<int>>(res.begin(), res.end());

}
};
```

- `if(i != 0 && nums[i] == nums[i-1]) continue;` 를 통한 탐색 범위 줄이기 최적화 정도의 차이로 상 / 하위 갈리는 정도
- 단순 2 pointer로 처리해도 무방


18 changes: 18 additions & 0 deletions climbing-stairs/haung921209.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
```cpp
class Solution {
public:
int climbStairs(int n) {
vector<int> dp = {0, 1, 2};
dp.resize(n+1);
for(int i=3;i<=n;i++){
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
```
- O(n)
- dp



47 changes: 47 additions & 0 deletions product-of-array-except-self/haung921209.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
- URL : https://leetcode.com/problems/product-of-array-except-self/description/
- points from constraints
- 2 <= nums.length <= 10^5
- if not use O(n) algorithm, a TLE occurs
- -30 <= nums[i] <= 30
- the production result can be negative
- do not use an unsigned type for the result object.
- The input is generated such that answer[i] is guaranteed to fit in a 32-bit integer.
- There is no need to use a 64-bit (or larger) type for the result object.
- However, it is not guaranteed that the intermediate object will always be a 32-bit type.



```cpp
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> idxOfZero;
long long productRes = 1;
for(int i=0;i<nums.size();i++){
if(nums[i]==0){
idxOfZero.push_back(i);
}else{
productRes *=nums[i];
}
}
vector<int> res(nums.size(), 0);
if(idxOfZero.size()>=2){
return res;
}else if(idxOfZero.size()==1){
res[idxOfZero[0]] = productRes;
return res;
}

for(int i=0;i<nums.size();i++){
res[i] = (int)(productRes / nums[i]);
}
return res;
}
};
```

- O(n)
- long long type for result object -> 64bit(by constraint #3)



70 changes: 70 additions & 0 deletions valid-anagram/haung921209.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@

```cpp
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length())
return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s==t;
}
};
```

- O(nlogn)
- std의 sort를 사용

```
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length())
return false;
unordered_map<char, int> dict;
for(auto c:s){
dict[c]++;
}
for(auto c:t){
if(dict[c]==0){
return false;
}
dict[c]--;
}
return true;

}
};
```

- O(n)? => O(nlogn)
- map insert에서 O(logn)씩 소요됨
- 위의 sort보다는 효율적일 수 있음

```cpp
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length())
return false;
vector<int>cntVec(26, 0);
for(auto c:s){
cntVec[(int(c-'a'))]++;
}
for(auto c:t){
cntVec[(int(c-'a'))]--;
}
for(auto cnt:cntVec){
if(cnt!=0){
return false;
}
}
return true;

}
};
```
- O(n)
- 두번째 것과 마찬가지로 저장공간이 필요하나, O(n)으로 종료 가능
- 시간 복잡도를 최대한 최적화 하는 경우

73 changes: 73 additions & 0 deletions validate-binary-search-tree/haung921209.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# 연관 링크
- [문제 풀이 스케줄](https://github.com/orgs/DaleStudy/projects/6/views/5)
- [답안 코드 제출법](https://github.com/DaleStudy/leetcode-study/wiki/%EB%8B%B5%EC%95%88-%EC%A0%9C%EC%B6%9C-%EA%B0%80%EC%9D%B4%EB%93%9C)

# Problem
- 문제 링크 : https://leetcode.com/problems/validate-binary-search-tree/
- 문제 이름 : validate-binary-search-tree
- 문제 번호 : 251
- 난이도 : medium
- 카테고리 : binary search tree

# 문제 설명

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.

#### Constraints:

- The number of nodes in the tree is in the range [1, 104].
- 2^31 <= Node.val <= 2^31 - 1

# 아이디어
- 각 노드 별



# 코드 (Solution)
```cpp

class Solution {
public:
bool isValidBSTHelper(TreeNode* root, long min, long max){
if (!root) {
return true;
}

if (root->val <= min || root->val >= max) {
return false;
}

return isValidBSTHelper(root->left, min, root->val) &&
isValidBSTHelper(root->right, root->val, max);
}

bool isValidBST(TreeNode* root) {
return isValidBSTHelper(root, LONG_MIN, LONG_MAX);
}
};
```

## 코드 설명

- INT_MIN / INT_MAX가 Constraint의 경계값이지만, 해당 값을 이용할 경우 경계값 비교 시 번거로워지므로 LONG으로 비교하도록 처리


# 최적화 포인트 (Optimality Discussion)
- 특이 사항 없음

# 🧪 테스트 & 엣지 케이스

## INT_MAX / INT_MIN으로 할 경우
- root = [2147483647] 인 경우 엣지 케이스

# 📚 관련 지식 복습

# 🔁 회고