日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

两数组的交集(无重复)Intersection of Two Arrays

發(fā)布時間:2025/3/20 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 两数组的交集(无重复)Intersection of Two Arrays 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。