티스토리 뷰

알고리즘

Intersection of Two Arrays 문제 (leetcode 349)

뮹뭉묵목몽묭 2019. 7. 23. 04:47

https://leetcode.com/problems/intersection-of-two-arrays/

 

Intersection of Two Arrays - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

두개의 배열이 주어지고 두개의 배열의 배열 값중 공통 되는 값을 찾는 문제이다.

주의 : output될때 공통 값은 중복되는 값이 없어야하마

         output값은 정렬된 상태 일 수도 있음(그럼 정렬된 상태가 아니여도 된다는 소리)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        
        //값을 저장할 리스트
        List<Integer> result = new ArrayList<Integer>();
//값을 판별한 해쉬맵
        Map<Integer, Boolean> TorF = new HashMap<>();
        //첫번째 배열 길이만큼 반복문 돌리고 해쉬맵에 키로 숫자를 집어넣고, 값으로 false를 집어넣음
         for (int num : nums1) {
            TorF.put(num, false);      
        }
       //두번째 배열 길이만큼 반복문 돌리고 해쉬맵에 각 숫자에 해당되는 키가 있는지 확인함 있으면
//값이 false인지를 확인함 true일 경우 해당 숫자가 이미 리스트에 저장되 있다는 뜻이므로 다음
//숫자로 이동함. 해당 숫자가 조건을 충족할 경우 리스트에 넣어줌
 
        for (int num : nums2) {
            if (TorF.containsKey(num) && TorF.get(num) == false) {
                result.add(num);
                TorF.put(num,true);      
            } 
        }
 
      //리스트 값들 배열로 바꾸는 과정
        int[] res = new int[result.size()];
        int k = 0;
        for (int num : result) 
            res[k++= num;
        return res;
    }
}
cs

 

'알고리즘' 카테고리의 다른 글

스택을 이용해서 큐 구현하기  (0) 2019.07.28
스택에 관하여  (0) 2019.07.25
Two Sum 문제 (leetcode 167)  (0) 2019.07.23
이진검색 문제 (leetcode 704번째 문제)  (0) 2019.07.22
선형 검색과 이진검색  (0) 2019.07.22
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함