BinarySearch 문제
leetcode.com/problems/intersection-of-two-arrays/
문제
두 배열의 교집합을 구하는 문제이다
ex) nums1 = [1,2,2,1], num2= [2,2]
답은 [2]
해결
2가지 방식으로 풀었다
Runtime은 Set은 6~7ms / BinarySearch가 5ms 걸렸다
1. Set (O(n))
static int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> numSet1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
Set<Integer> numSet2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
Set<Integer> result = new HashSet<>();
for (int num : numSet2) if (numSet1.contains(num)) result.add(num);
return result.stream().mapToInt(x->x).toArray();
}
2. BinarySearch (O(nlogn))
static int[] intersection_binary(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Set<Integer> result = new HashSet<>();
for (int num : nums2) if (binary_search(nums1, num)) result.add(num);
return result.stream().mapToInt(x->x).toArray();
}
static boolean binary_search(int[] arr, int key) {
int low = 0;
int high = arr.length-1;
while (low <= high) {
int mid = (low + high) / 2;
int midVal = arr[mid];
if (midVal < key) {
low = mid+1;
} else if (midVal > key) {
high = mid-1;
} else {
return true;
}
}
return false;
}
'Algorithm > Leetcode' 카테고리의 다른 글
[Leetcode(릿코드)] 107. Binary Tree Level Order Traversal II (Easy) (0) | 2020.11.01 |
---|---|
[Leetcode(릿코드)] 111. Minimum Depth of Binary Tree (Easy) (0) | 2020.11.01 |
[Leetcode(릿코드)] 441. Arranging Coins (Easy) (0) | 2020.10.28 |
[Leetcode(릿코드)] 746. Min Cost Climbing Stairs (Easy) (0) | 2020.10.25 |
[Leetcode(릿코드)] 997. Find the Town Judge (Easy) (0) | 2020.09.04 |
댓글