본문 바로가기
Java/리트코드

[리트코드][Java] 350. Intersection of Two Arrays II 두 배열의 교차점2

by 2D3 2023. 1. 9.
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

    댓글