728x90
Contents
문제 설명
두 개의 정수 배열 num1과 num2가 주어지면 교차점의 배열을 반환합니다.
결과의 각 요소는 두 배열에 표시된 횟수만큼 나타나야 하며, 원하는 순서로 결과를 반환할 수 있습니다.
예시
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.
문제 풀이
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
int n1 = nums1.length;
int n2 = nums2.length;
List<Integer> result = new ArrayList<>();
while(i < n1 && j < n2) {
if(nums1[i] == nums2[j]) {
result.add(nums1[i]);
i++;
j++;
}
else if(nums1[i] < nums2[j]) {
i++;
}
else if(nums1[i] > nums2[j]) {
j++;
}
}
return result.stream().mapToInt(n -> n).toArray();
}
}
728x90
'Java > 리트코드' 카테고리의 다른 글
[리트코드][Java] 566. Reshape the Matrix 행렬을 바꿔라 (0) | 2023.01.09 |
---|---|
[리트코드][Java] 121. Best Time to Buy and Sell Stock 주식을 사고 팔 최적의 시기 (0) | 2023.01.09 |
[리트코드][Java] 88. Merge Sorted Array 병합 정렬 (0) | 2023.01.04 |
[리트코드][Java] 1. Two Sum 두개의 합 (0) | 2023.01.04 |
[리트코드][Java] 53. Maximum Subarray 하위배열의 최댓값! (0) | 2023.01.04 |
댓글