package com.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; //求兩個數組的交集 public class FindIntersectionBetweenTwoArrays { //算法一:暴力搜索,時間復雜度O(n^2),空間復雜度O(1) public ArrayList<Integer> getIntersection(int[] arr, int[] arr2) { ArrayList<Integer> res = new ArrayList<Integer>(); if(arr == null || arr.length == 0 || arr2 == null || arr2.length == 0) { return res; } for(int i = 0;i < arr.length;i ++) { int temp = arr[i]; for(int j = 0;j < arr.length;j ++) { if(arr2[j] == temp && !res.contains(temp)) { res.add(temp); break; } } } return res; } //算法二:先排序,然后定義兩個指針,時間復雜度O(nlogn) (排序),空間復雜度O(1) public ArrayList<Integer> getIntersection2(int[] arr, int[] arr2) { ArrayList<Integer> res = new ArrayList<Integer>(); if(arr == null || arr.length == 0 || arr2 == null || arr2.length == 0) { return res; } Arrays.sort(arr); Arrays.sort(arr2); int i = 0; int j = 0; while(i < arr.length && j < arr2.length) { if(arr[i] < arr2[j]) { i ++; } else if(arr[i] > arr2[j]) { j ++; } else { if(!res.contains(arr[i])) { res.add(arr[i]); } i ++; j ++; } } return res; } //算法三:map計數,時間復雜度O(n),空間復雜度O(n),空間換時間 public ArrayList<Integer> getIntersection3(int[] arr, int[] arr2) { ArrayList<Integer> res = new ArrayList<Integer>(); if(arr == null || arr.length == 0 || arr2 == null || arr2.length == 0) { return res; } Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0;i < arr.length;i ++) { int key = arr[i]; if(map.containsKey(key)) { int value = map.get(key); value ++; map.put(key, value); } else { map.put(key, 1); } } for(int i = 0;i < arr2.length;i ++) { int key = arr2[i]; if(map.containsKey(key) && !res.contains(key)) { res.add(key); } } return res; } public static void main(String[] args) { int[] arr = {1,2,5,3,3,4}; int[] arr2 = {2,3,3,4,5,6}; FindIntersectionBetweenTwoArrays fb = new FindIntersectionBetweenTwoArrays(); List<Integer> res = fb.getIntersection3(arr, arr2); System.out.println(res); } } ———————————————— 版權聲明:本文為CSDN博主「奇零可草」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/zhou15755387780/article/details/81317561