Skip to content
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

[minji-go] Week 2 #732

Merged
merged 10 commits into from
Dec 21, 2024
37 changes: 37 additions & 0 deletions 3sum/minji-go.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
Problem: https://leetcode.com/problems/3sum/
Description: return all the triplets (i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0)
Concept: Array, Two Pointers, Sorting
Time Complexity: O(N²), Runtime 1107ms
Space Complexity: O(N), Memory 54.20MB
*/
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Map<Integer, Integer> number = new HashMap<>();
for(int i=0; i<nums.length; i++) {
number.put(nums[i], number.getOrDefault(nums[i], 0)+1);
}

Arrays.sort(nums);
Set<List<Integer>> set = new HashSet<>();
List<List<Integer>> triplets = new ArrayList<>();
List<Integer> lastTriplet = null;
for(int i=0; i<nums.length-1; i++) {
for(int j=i+1; j<nums.length; j++){
int twoSum = nums[i]+nums[j];
if(nums[j]>-twoSum) continue;

int count = number.getOrDefault(-twoSum,0);
if(nums[i]==-twoSum) count--;
if(nums[j]==-twoSum) count--;
if(count<=0) continue;

List<Integer> triplet = List.of(nums[i], nums[j], -twoSum);
int setSize = set.size();
set.add(triplet);
if(setSize != set.size()) triplets.add(triplet);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. set을 사용해서 중복된 결과일 때 triplet에 추가하지 않는 방식도 유효하지만
    정렬된 배열을 사용하고 있기 때문에 요소가 이전 값과 같을 경우 건너 뛰는 방식으로도 중복을 제거할 수 있어요

  2. two pointer를 배열의 양쪽 끝부터 이동하는 방식도 추천드립니다!

  • i를 고정하고 j, k를 이동하는 방식

Copy link
Contributor Author

@minji-go minji-go Dec 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Runtime에 아쉬움이 있었는데, 새로운 방법을 많이 제안해주셔서 생각해볼 수 있어서 너무 좋았습니다!
혼자서 다시 보려면 힘든데, 짚어주시니까 수월하게 볼 수 있어서 좋네요! 감사합니다 :)

}
}
return triplets;
}
}
21 changes: 21 additions & 0 deletions climbing-stairs/minji-go.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
Problem: https://leetcode.com/problems/climbing-stairs/
Description: how many distinct ways can you climb to the top, if you can either climb 1 or 2 steps
Concept: Dynamic Programming, Memoization, Recursion, Math, Array, Iterator, Combinatorics ...
Time Complexity: O(n), Runtime: 0ms
Space Complexity: O(1), Memory: 40.63MB
*/
class Solution {
public int climbStairs(int n) {
if(n==1) return 1;
if(n==2) return 2;

int prev=1, cur=2;
for(int i=3; i<=n; i++){
int next=prev+cur;
prev=cur;
cur=next;
}
return cur;
}
}
Copy link
Member

@dusunax dusunax Dec 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생하셨습니다!

저는 혼자 풀다가 테스트케이스 통과가 안되서 ChatGPT의 도움을 받고
알고달레 문제 해설을 보면서 개념 정리를 했는데요

스스로 푸신 것 같아서 멋집니다🥹
재귀로도 다시 한 번 풀어보시면 좋을 것 같아요

Copy link
Contributor Author

@minji-go minji-go Dec 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dusunax 선아님도 이번주 고생하셨습니다!
1주차에 비해 문제가 어려워서 푸는데 시간이 좀 더 걸렸던 거 같습니다 ㅎㅎ

Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
Problem: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
Description: Given two integer arrays preorder and inorder, construct and return the binary tree.
Concept: Array, Hash Table, Divide and Conquer, Tree, Binary Tree
Time Complexity: O(NM), Runtime 2ms
Space Complexity: O(N), Memory 45.02MB
*/
import java.util.HashMap;
import java.util.Map;

class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
boolean isLeft = true;
Map<Integer, TreeNode> parents = new HashMap<>();
TreeNode rootNode = null, parentNode = null;

for (int pidx=0, iidx=0; pidx<preorder.length; pidx++) {
int pval = preorder[pidx];
int ival = inorder[iidx];

if(pidx==0) {
rootNode = parentNode = new TreeNode(pval);
} else if (isLeft) {
parents.put(pval, parentNode);
parentNode = parentNode.left = new TreeNode(pval);
} else {
isLeft = true;
parents.put(pval, parentNode);
parentNode = parentNode.right = new TreeNode(pval);
}

if(pval==ival) {
isLeft = false;
TreeNode targetNode = parentNode;
while (iidx<inorder.length-1 && parents.get(parentNode.val)!=null) {
if(parentNode.val == inorder[iidx+1]){
iidx++;
targetNode = parentNode;
}
parentNode = parents.get(parentNode.val);
}
if(iidx<inorder.length-1 && parentNode.val != inorder[iidx+1]){
iidx++;
parentNode = targetNode;
} else iidx = iidx+2;
}
}

return rootNode;
}
}

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
28 changes: 28 additions & 0 deletions decode-ways/minji-go.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
Problem: https://leetcode.com/problems/decode-ways/
Description: Given a string s containing only digits, return the number of ways to decode it
Concept: String, Dynamic Programming
Time Complexity: O(N), Runtime 1ms
Space Complexity: O(N), Memory 42.12MB
*/
class Solution {
public int numDecodings(String s) {
int[] dp = new int[s.length()];
if(decode(s.substring(0, 1))) dp[0]=1;
if(s.length()>1 && decode(s.substring(1, 2))) dp[1]+=dp[0];
if(s.length()>1 && decode(s.substring(0, 2))) dp[1]+=dp[0];

for(int i=2; i<s.length(); i++){
if(decode(s.substring(i,i+1))) dp[i]+=dp[i-1];
if(decode(s.substring(i-1,i+1))) dp[i]+=dp[i-2];
}
return dp[s.length()-1];
}

public boolean decode(String s){
int num = Integer.parseInt(s);
int numLength = (int) Math.log10(num) + 1;
if(num<0 || num>26 || numLength != s.length()) return false;
return true;
}
}
25 changes: 25 additions & 0 deletions valid-anagram/minji-go.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Problem: https://leetcode.com/problems/valid-anagram/
Description: return true if one string is an anagram of the other, one formed by rearranging the letters of the other
Concept:String, Hash Table, Sorting, Array, Counting, String Matching, Ordered Map, Ordered Set, Hash Function ...
Time Complexity: O(n), Runtime: 27ms
Space Complexity: O(n), Memory: 43.05MB
*/
import java.util.HashMap;
import java.util.Map;

class Solution {
public boolean isAnagram(String s, String t) {
if(s.length() != t.length()) return false;

Map<Character, Integer> charCount = new HashMap<>();
for(int i=0; i<s.length(); i++){
charCount.put(s.charAt(i), charCount.getOrDefault(s.charAt(i), 0)+1);
charCount.put(t.charAt(i), charCount.getOrDefault(t.charAt(i), 0)-1);
}
for(Integer count : charCount.values()){
if(count !=0) return false;
}
return true;
}
}
Loading