-
Intersection of Two Arrays알고리즘 2019. 7. 29. 17:05
LeetCode 349번
Tags. hash table, binary Search, Two Pointers, Sort
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.
Code
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748class Solution {public int[] intersection(int[] nums1, int[] nums2) {nums1 = notagain(nums1);nums2 = notagain(nums2);List<Integer> solution = new ArrayList<>();for(int i = 0; i < nums1.length; i++) {for(int j = 0; j < nums2.length; j++) {if(nums1[i] == nums2[j]) {solution.add(nums1[i]);}}}int[] result = new int[solution.size()];for(int i = 0; i < solution.size(); i++) {result[i] = solution.get(i);}return result;}static int[] notagain(int[] arr) {int[] result = {};Map<Integer, Integer> arrMap = new HashMap<>();for(int i = 0; i < arr.length; i++) {int key = arr[i];int value = arr[i];arrMap.put(key, value);}Set set = arrMap.keySet();Iterator iterator = set.iterator();result = new int[arrMap.size()];int i = 0;while(iterator.hasNext()){int key = (int)iterator.next();result[i] = key;i++;}return result;}}cs Solution
두개의 배열에 중복되는 값을 순서에 상관없이 배열로 반환하는 문제이다.
leetcode상에서 주어진 topic으로는 hashtable이 있었지만 hashmap으로 코드를 작성했다
과정으로는
1. 두개의 배열의 중복된 값을 없애기 위한 메소드를 만들고 중복을 없애기 위해 hashmap의 key와 value값을 배열의 값으로 동일하게 주었다.
2. Set으로 map의 key값을 담아주고 iterator로 원소를 순회하며 배열을 새로 생성해준다.
3. 만들어진 두개의 배열을 for문으로 값이 동일할때 List에 담아주고
4. List의 값을 다시 배열에 담에 결과를 반환한다.
Runtime : 8ms
Memory : 36.5MB
'알고리즘' 카테고리의 다른 글
Next Greater Element I (0) 2019.07.29 Backspace String Compare (0) 2019.07.29 Peak Index in a Mountain Array (0) 2019.07.29 Two Sum II - Input array is sorted (0) 2019.07.29 Binary Search (0) 2019.07.23