把数组转成哈希集合,就可以 O(1) 判断元素是否在数组中了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int[] findIntersectionValues(int[] nums1, int[] nums2) { HashSet<Integer>set1=new HashSet<>(); for(int x:nums1){ set1.add(x); } HashSet<Integer>set2=new HashSet<>(); for(int x:nums2){ set2.add(x); } int n1=0,n2=0; for(int x:nums1){ if(set2.contains(x)){ n1++; } } for(int x:nums2){ if(set1.contains(x)){ n2++; } } return new int[]{n1,n2}; } }
|