349. Intersection of Two Arrays
class Solution { public int[] intersection(int[] nums1, int[] nums2) { Arrays.sort(nums1); Arrays.sort(nums2); Set<Integer> set = new HashSet<>(); int i = 0; int j = 0; while(i < nums1.length && j < nums2.length){ if(nums1[i] == nums2[j]){ set.add(nums1[i]); i++; j++; }else if (nums1[i] > nums2[j]){ j++; }else{ i++; } } int[] result = new int[set.size()]; int q = 0; for(Integer num : set){ result[q++] = num; } return result; } }
https://leetcode.com/problems/intersection-of-two-arrays/discuss/81969/Three-Java-Solutions
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.
posted on 2018-07-18 08:50 猪猪🐷 阅读(89) 评论(0) 收藏 举报
浙公网安备 33010602011771号