题目链接:
https://leetcode-cn.com/problems/intersection-of-two-arrays/
解题思路:
把其中一个放进hashmap或者hashset,然后另一个去遍历,如果找到了,题目要求唯一,那就删掉hashset里面。如果不唯一,那就hashmap里面的count-1,然后直到count==0,删除。
1 class Solution { 2 public int[] intersection(int[] nums1, int[] nums2) { 3 Set<Integer> hash = new HashSet<>(); 4 int [] a = new int[nums1.length]; 5 for(int i=0;i<nums1.length;i++) 6 { 7 hash.add(nums1[i]); 8 } 9 int x=0; 10 for(int j=0;j<nums2.length;j++) 11 { 12 if(hash.contains(nums2[j])) 13 { 14 a[x] = nums2[j]; 15 hash.remove(nums2[j]); 16 x++; 17 } 18 } 19 20 int []tt =new int[x]; 21 for(int i=0;i<x;i++) 22 { 23 tt[i] = a[i]; 24 } 25 return tt; 26 } 27 }
1 class Solution { 2 public int[] intersect(int[] nums1, int[] nums2) { 3 Map<Integer,Integer> hash =new HashMap<>(); 4 for(int i=0;i<nums1.length;i++) 5 { 6 if(hash.containsKey(nums1[i])) 7 { 8 int count=hash.get(nums1[i]); 9 hash.put(nums1[i],count+1); 10 } 11 else 12 { 13 hash.put(nums1[i],1); 14 } 15 } 16 int []a =new int [nums2.length]; 17 int x=0; 18 for(int i=0;i<nums2.length;i++) 19 { 20 if(hash.containsKey(nums2[i])) 21 { 22 a[x] =nums2[i]; 23 x++; 24 int count = hash.get(nums2[i]); 25 count =count-1; 26 hash.put(nums2[i],count); 27 if(hash.get(nums2[i])==0){ //值为0 则map中没有这个键 删除键 28 hash.remove(nums2[i]); 29 } 30 } 31 } 32 int[]result = new int[x]; 33 for(int i = 0;i<x;i++) 34 { 35 result[i] = a[i]; 36 } 37 return result; 38 } 39 }
class Solution { public int[] intersect(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; ArrayList<Integer> mid = new ArrayList<>(); Arrays.sort(nums1); Arrays.sort(nums2);//先排序,然后大小大小的搞 int i=0; int j=0; int k=0; while(i<m && j<n) { if(nums1[i]==nums2[j]) { mid.add(nums1[i]); i++; j++; k++; } else if (nums1[i]<nums2[j]) { i++; } else { j++; } } int [] res = new int[k]; for(int x=0;x<mid.size();x++) { res[x] = mid.get(x); } return res; } }