两数组的交集(无重复)Intersection of Two Arrays
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
問題:
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.
解決:
①使用hashSet保存nums1數(shù)組中的值,然后比較即可。耗時5ms.
public class Solution {
? ? public int[] intersection(int[] nums1, int[] nums2) {
? ? ?? ?List<Integer> list = new ArrayList<>();
? ? ? ? Set<Integer> set = new HashSet<>();
? ? ? ? for (int n : nums1) {
? ? ? ? ?? ?set.add(n);
? ? ? ? }
? ? ? ? for (int n : nums2) {
? ? ? ? ?? ?if (set.contains(n)) {
? ? ? ? ?? ??? ?list.add(n);
? ? ? ? ?? ??? ?set.remove(n);
? ? ? ? ?? ?}
? ? ? ? }
? ? ? ? int res[] = new int[list.size()];
? ? ? ? for(int i = 0;i < list.size();i ++ ){
? ? ? ? ? ? res[i] = list.get(i);
? ? ? ? }
? ? ? ? return res;
? ? }
}
②使用雙指針法, 使用一個臨時數(shù)組保存相同的數(shù)值,當(dāng)掃描時存在與臨時數(shù)組最后一個值相同的數(shù)時,跳過,否則,添加到臨時數(shù)組中。
public class Solution {
? ? public int[] intersection(int[] nums1, int[] nums2) {
? ? ? ? if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) return new int[0];
? ? ? ? Arrays.sort(nums1);
? ? ? ? Arrays.sort(nums2);
? ? ? ? int temp[] = new int[nums1.length];
? ? ? ? int p1 = 0;
? ? ? ? int p2 = 0;
? ? ? ? int p = 0;
? ? ? ? while(p1 < nums1.length && p2 < nums2.length){
? ? ? ? ? ? if (nums1[p1] == nums2[p2]) {
? ? ? ? ? ? ? ? if (p - 1 >= 0 && temp[p - 1] == nums1[p1]) {//相同的值重復(fù)
? ? ? ? ? ? ? ? ? ? //什么都不做
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? temp[p] = nums1[p1];
? ? ? ? ? ? ? ? ? ? p ++;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? p1 ++;
? ? ? ? ? ? ? ? p2 ++;
? ? ? ? ? ? }else if (nums1[p1] < nums2[p2]) {
? ? ? ? ? ? ? ? p1 ++;
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? p2 ++;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? int res[] = new int[p];
? ? ? ? for (int i = 0;i < p ;i ++ ) {
? ? ? ? ? ? res[i] = temp[i];
? ? ? ? }
? ? ? ? return res;
? ? }
}
轉(zhuǎn)載于:https://my.oschina.net/liyurong/blog/993827
總結(jié)
以上是生活随笔為你收集整理的两数组的交集(无重复)Intersection of Two Arrays的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库执行计划慢导致I/O 慢
- 下一篇: 测试与CMMI质量体系