|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=349 lang=java |
| 3 | + * |
| 4 | + * [349] 两个数组的交集 |
| 5 | + * |
| 6 | + * https://leetcode-cn.com/problems/intersection-of-two-arrays/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (69.29%) |
| 10 | + * Likes: 200 |
| 11 | + * Dislikes: 0 |
| 12 | + * Total Accepted: 77.4K |
| 13 | + * Total Submissions: 111K |
| 14 | + * Testcase Example: '[1,2,2,1]\n[2,2]' |
| 15 | + * |
| 16 | + * 给定两个数组,编写一个函数来计算它们的交集。 |
| 17 | + * |
| 18 | + * |
| 19 | + * |
| 20 | + * 示例 1: |
| 21 | + * |
| 22 | + * 输入:nums1 = [1,2,2,1], nums2 = [2,2] |
| 23 | + * 输出:[2] |
| 24 | + * |
| 25 | + * |
| 26 | + * 示例 2: |
| 27 | + * |
| 28 | + * 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] |
| 29 | + * 输出:[9,4] |
| 30 | + * |
| 31 | + * |
| 32 | + * |
| 33 | + * 说明: |
| 34 | + * |
| 35 | + * |
| 36 | + * 输出结果中的每个元素一定是唯一的。 |
| 37 | + * 我们可以不考虑输出结果的顺序。 |
| 38 | + * |
| 39 | + * |
| 40 | + */ |
| 41 | + |
| 42 | +// @lc code=start |
| 43 | +class Solution { |
| 44 | + public int[] intersection(int[] nums1, int[] nums2) { |
| 45 | + Arrays.sort(nums2); |
| 46 | + |
| 47 | + Set<Integer> set = new HashSet<>(); |
| 48 | + for (int num : nums1) { |
| 49 | + if (!set.contains(num) && bsearch(nums2, num)) { |
| 50 | + set.add(num); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + int[] result = new int[set.size()]; |
| 55 | + int index = 0; |
| 56 | + for (int num : set) { |
| 57 | + result[index++] = num; |
| 58 | + } |
| 59 | + |
| 60 | + return result; |
| 61 | + } |
| 62 | + |
| 63 | + public boolean bsearch(int[] nums, int target) { |
| 64 | + int left = 0; |
| 65 | + int right = nums.length - 1; |
| 66 | + |
| 67 | + while (left <= right) { |
| 68 | + int mid = left + (right - left) / 2; |
| 69 | + if (nums[mid] == target) { |
| 70 | + return true; |
| 71 | + } else if (nums[mid] < target) { |
| 72 | + left = mid + 1; |
| 73 | + } else if (nums[mid] > target) { |
| 74 | + right = mid - 1; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return false; |
| 79 | + } |
| 80 | +} |
| 81 | +// @lc code=end |
| 82 | + |
0 commit comments