description:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
解题思路: 使用排序算法然后再进行处理,注意当比较两个数组相等的时候,要排除相同的数据的情况,也就是一个选代表的过程,当两个数字是相等时也要注意同时将数组的下表加一。
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
return null;
}
Arrays.sort(nums1);
Arrays.sort(nums2);
int[] arr = new int[Math.min(nums1.length, nums2.length)];
int i = 0, j = 0, index = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
if (index == 0 || arr[index - 1] != nums1[i]) {
arr[index++] = nums1[i];
}
j++;
i++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
i++;
}
}
int[] result = new int[index];
for (int k = 0; k < index; k++) {
result[k] = arr[k];
}
return result;
}
}