Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions two-sum/forest000014.java
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 {
Copy link
Contributor

Choose a reason for hiding this comment

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

안녕하세요, @forest000014 님! 저도 java를 사용하여 이번 스터디에 참여하고 있습니다. 잘 부탁드립니다.
튜플 클래스를 따로 사용하여 주신 점이 저는 개인적으로 가독성이 좋아 코드를 이해하는 것이 더 수월했습니다.
3주차 문제 풀이 수고 많으셨습니다!

public final Integer ref;
public final Integer val;

public Tuple(Integer ref, Integer val) {
this.ref = ref;
this.val = val;
}
}
}