-
-
Notifications
You must be signed in to change notification settings - Fork 245
[forest000014] Week 03 #785
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
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
494d56e
Two Sum
forest000014 b6138ed
Two Sum - 마지막 개행 문자
forest000014 8681b04
Reverse Bits
forest000014 65e2454
Product of Array Except Self
forest000014 9c068d6
Product of Array Except Self - space complexity O(1)
forest000014 9c1fff6
Maximum Subarray
forest000014 d818f00
Combination Sum
forest000014 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
/* | ||
time complexity: O(nlogn) | ||
- nums 배열(=candidates) 정렬: O(nlogn) | ||
- 재귀 호출 부분은 시간 복잡도를 계산하기가 어렵네요.. candidates 배열을 정렬해두어서, target까지 남은 차이가 현재 확인하고 있는 candidate보다 작다면 루프를 빠져나오게 해서 O(n^t)보다는 작을 텐데, 이런 경우에는 어떻게 표현해야 적절한지 잘 모르겠습니다. | ||
|
||
space complexity: O(1) - 정답으로 사용한 이중 List는 제외 | ||
|
||
*/ | ||
|
||
class Solution { | ||
ArrayList<Integer> nums; | ||
|
||
public List<List<Integer>> combinationSum(int[] candidates, int target) { | ||
nums = Arrays.stream(candidates) | ||
.boxed() | ||
.collect(Collectors.toCollection(ArrayList::new)); | ||
|
||
Collections.sort(nums); | ||
|
||
return calc(target, 0); | ||
} | ||
|
||
private List<List<Integer>> calc(int target, int curr) { | ||
if (target == 0) { | ||
ArrayList<List<Integer>> lists = new ArrayList<>(); | ||
lists.add(new ArrayList<>()); | ||
return lists; | ||
} | ||
|
||
List<List<Integer>> ret = new ArrayList<>(); | ||
boolean found = false; | ||
for (int i = curr; i < nums.size() && nums.get(i) <= target; i++) { | ||
List<List<Integer>> results = calc(target - nums.get(i), i); | ||
for (List<Integer> result : results) { | ||
result.add(nums.get(i)); | ||
ret.add(result); | ||
} | ||
} | ||
return ret; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
/* | ||
time complexity: O(n) | ||
space complexity: O(1) | ||
|
||
왼쪽에서부터 누적합을 구하되, 더한 값이 음수가 되는 순간 지금까지 더한 값을 버린다. (즉, 지금까지의 원소는 모두 subarray에서 제외한다.) 이렇게 누적합을 계산하면서, 누적합의 최대값을 찾으면 답이 된다. | ||
|
||
단, 모든 원소가 음수인 경우는 예외적으로 처리해준다. | ||
|
||
*/ | ||
|
||
class Solution { | ||
public int maxSubArray(int[] nums) { | ||
int n = nums.length; | ||
int ans = -10001; | ||
int max = -10001; | ||
int sum = 0; | ||
for (int i = 0; i < n; i++) { | ||
if (sum + nums[i] < 0) { | ||
sum = 0; | ||
} else { | ||
sum += nums[i]; | ||
} | ||
if (sum > ans) { | ||
ans = sum; | ||
} | ||
if (max < nums[i]) { | ||
max = nums[i]; | ||
} | ||
} | ||
|
||
// 모두 음수인 경우의 예외 처리 | ||
if (max < 0) { | ||
return max; | ||
} else { | ||
return ans; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
/* | ||
runtime 8 ms, beats 4.87% | ||
memory 55.44 MB, beats 54.17% | ||
|
||
time complexity: O(n) | ||
- nums 각각의 원소를 소인수분해 : O(10 * n) = O(n) | ||
- ans[] 배열 계산 : O(10 * n) | ||
- i, j, k의 3중 for-loop가 O(n * 10 * 4) 처럼 보일 수 있는데요(10은 소인수 분해 base의 개수, 4는 power중 최대값), | ||
- 실제로는 k가 큰 경우에는 j-loop가 일찍 끝나고 (예컨대 nums[i] = 2^4 인 경우에는, base가 2에서 끝나니 j-loop가 j=1에서 끝남) | ||
- j가 큰 경우에는 k-loop가 일찍 끝나므로 (예컨대 num[i] = 29인 경우에는, k-loop가 1에서 끝남) | ||
- 최악의 경우에 O(n * 10) 정도로 보는 게 타당하다고 생각합니다. | ||
|
||
space complexity: O(1) | ||
|
||
[풀이] | ||
나눗셈이 금지되어 있기 때문에, 최대한 곱할 수 있는 만큼을 미리 곱해놓고, i번째 원소마다 부족한 부분만큼을 나중에 채워 넣어 곱해주는 방식으로 접근했습니다. | ||
nums[i]의 절대값이 30 이하인 점에 착안해서, nums[i]는 많아야 10개의 base로 소인수 분해가 가능하다는 점을 떠올렸습니다. 따라서 각각의 base마다 (nums 전체에서 등장한 base의 지수의 총합) - (nums[i]의 base의 지수 중 가장 큰 값) 만큼의 지수로 미리 곱해주고, i에 대한 iteration에서 부족한 지수만큼을 보충해서 곱해주었습니다. | ||
(풀이를 쓰다 보니, 실제 코드에서 이렇게 미리 곱해 놓은 수를 base라고 명명한 게 혼동될 수 있겠네요...^^;) | ||
|
||
이 풀이에서 아쉬운 점이 여전히 있습니다. 시간 복잡도를 따지면 O(10*n) = O(n)이니 문제의 조건을 맞췄다고 할 수도 있겠지만, 상수가 좀 크다는 점이 마음에 걸리네요. | ||
(for (int j = 0; j < 10 && abs > 1; j++) <--- 여기에서 abs == 1이 되면 for-loop를 빠져나가게 했지만, nums[i]가 모두 29로 차있는 edge case라면 10*n을 꽉 채우게 되니까요.) | ||
그래도 어쨌든 문제의 조건을 최대한 활용해서 시도해볼만한 접근이라고 생각합니다. | ||
|
||
이 풀이 말고도, nums[]를 2개로 나눈 블럭, 4개로 나눈 블럭, 8개로 나눈 블럭, ... 이런 식으로 사이즈 별로 블럭을 나눠두고, 각각의 블럭 내부의 곱을 미리 계산해두는 방식도 생각해보았습니다. 이러면 시간 복잡도와 공간 복잡도가 모두 O(nlogn)이 나올 것 같습니다. (사실 이 풀이를 가장 처음에 떠올렸습니다만, O(n)으로 줄이는 고민을 하다가 현재 제출한 풀이를 떠올리고서는 이 풀이는 구현을 안 했습니다. 시간이 되면 이렇게도 풀어보고, 좀 더 디벨롭을 해봐야겠네요.) | ||
*/ | ||
class Solution { | ||
public int[] productExceptSelf(int[] nums) { | ||
int n = nums.length; | ||
|
||
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; | ||
int[] sumPowers = new int[10]; | ||
int[] maxPowers = new int[10]; | ||
|
||
int base = 1; | ||
|
||
int[] ans = new int[n]; | ||
|
||
for (int i = 0; i < n; i++) { | ||
if (nums[i] == 0) { | ||
int x = 1; | ||
for (int j = 0; j < n; j++) { | ||
if (j == i) { | ||
continue; | ||
} | ||
ans[j] = 0; | ||
x *= nums[j]; | ||
} | ||
ans[i] = x; | ||
|
||
return ans; | ||
} | ||
|
||
int abs; | ||
if (nums[i] > 0) { | ||
abs = nums[i]; | ||
} else { | ||
abs = -nums[i]; | ||
base = -base; | ||
} | ||
|
||
for (int j = 0; j < 10 && abs > 1; j++) { | ||
int curPower = 0; | ||
while (abs % primes[j] == 0) { | ||
sumPowers[j]++; | ||
curPower++; | ||
abs /= primes[j]; | ||
} | ||
if (curPower > maxPowers[j]) { | ||
maxPowers[j] = curPower; | ||
} | ||
} | ||
} | ||
|
||
for (int i = 0; i < 10; i++) { | ||
for (int j = 0; j < sumPowers[i] - maxPowers[i]; j++) { | ||
base *= primes[i]; | ||
} | ||
} | ||
|
||
for (int i = 0; i < n; i++) { | ||
ans[i] = base; | ||
for (int j = 0; j < 10; j++) { | ||
int tmp = nums[i]; | ||
int power = 0; | ||
while (tmp % primes[j] == 0) { | ||
power++; | ||
tmp /= primes[j]; | ||
} | ||
for (int k = 0; k < maxPowers[j] - power; k++) { | ||
ans[i] *= primes[j]; | ||
} | ||
} | ||
if (nums[i] < 0) { | ||
ans[i] = -ans[i]; | ||
} | ||
} | ||
|
||
|
||
return ans; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/* | ||
runtime 0 ms, beats 100.00% | ||
memory 41.47 MB, beats 90.14% | ||
|
||
time complexity: O(1) | ||
space complexity: O(1) | ||
|
||
i번째 bit를 구하고, 이를 ans(초기값 0)의 31-i번째 자리에 bitwise-OR 연산을 하여, bit 위치를 reverse 했습니다. | ||
*/ | ||
|
||
public class Solution { | ||
// you need treat n as an unsigned value | ||
public int reverseBits(int n) { | ||
int x = 1; | ||
int ans = 0; | ||
for (int i = 0; i < 32; i++) { | ||
int bit = (x & n) >>> i; | ||
bit <<= (31 - i); | ||
ans |= bit; | ||
x <<= 1; | ||
} | ||
return ans; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
/* | ||
runtime 23 ms, beats 50.28% | ||
memory 45.12 MB, beats 20.14% | ||
|
||
time complexity: O(nlogn) | ||
- numsArray 정렬: O(nlogn) | ||
- binary search: O(nlogn) | ||
- i iteration: O(n) | ||
- i번째 binary search: O(logn) | ||
|
||
space complexity: O(n) | ||
- numsArray: O(n) | ||
*/ | ||
|
||
class Solution { | ||
public int[] twoSum(int[] nums, int target) { | ||
ArrayList<Tuple> numsArray = IntStream.range(0, nums.length) | ||
.mapToObj(i -> new Tuple(i, nums[i])) | ||
.collect(Collectors.toCollection(ArrayList::new)); | ||
|
||
numsArray.sort(Comparator.comparing(tuple -> tuple.val)); | ||
|
||
int n = numsArray.size(); | ||
|
||
for (int i = 0; i < n; i++) { | ||
int x = target - numsArray.get(i).val; | ||
int j = -1; | ||
int l = i + 1; | ||
int r = n - 1; | ||
boolean found = false; | ||
while (l <= r) { | ||
int m = (r - l) / 2 + l; | ||
if (numsArray.get(m).val == x) { | ||
j = m; | ||
found = true; | ||
break; | ||
} else if (numsArray.get(m).val < x) { | ||
l = m + 1; | ||
} else { | ||
r = m - 1; | ||
} | ||
} | ||
|
||
if (found) { | ||
int[] ans = new int[2]; | ||
ans[0] = numsArray.get(i).ref; | ||
ans[1] = numsArray.get(j).ref; | ||
return ans; | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
|
||
public class Tuple { | ||
public final Integer ref; | ||
public final Integer val; | ||
|
||
public Tuple(Integer ref, Integer val) { | ||
this.ref = ref; | ||
this.val = val; | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
안녕하세요, @forest000014 님! 저도 java를 사용하여 이번 스터디에 참여하고 있습니다. 잘 부탁드립니다.
튜플 클래스를 따로 사용하여 주신 점이 저는 개인적으로 가독성이 좋아 코드를 이해하는 것이 더 수월했습니다.
3주차 문제 풀이 수고 많으셨습니다!