问题描述:给你两个数组,找出它们的公共数字。
思路:通过map对已有数字进行存储读取。
原答案:
public int[] intersection(int[] nums1, int[] nums2) {
int length=nums1.length;
Map<Integer,Boolean> map=new HashMap<Integer,Boolean>();
Map<Integer,Boolean> resMap=new HashMap<Integer,Boolean>();
List<Integer> list=new ArrayList<Integer>();
for(int i=0;i<length;i++){
map.put(nums1[i],true);
}
length=nums2.length;
for(int j=0;j<length;j++){
if(map.containsKey(nums2[j])&&(!resMap.containsKey(nums2[j]))){
resMap.put(nums2[j],true);
list.add(nums2[j]);
}
}
int size=list.size();
int[] res=new int[size];
for(int k=0;k<size;k++){
res[k]=list.get(k);
}
return res;
}
最佳答案:
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) return new int[0];
List<Integer> res = new ArrayList<>();
int max = nums1[0], min = nums1[0];
for (int i = 1; i < nums1.length; i++){
if (nums1[i] > max) max = nums1[i];
else if (nums1[i] < min) min = nums1[i];
}
boolean[] bucket = new boolean[max - min + 1];
for (int num: nums1) bucket[num - min] = true;
for (int num: nums2){
if (num >= min && num <= max){
if (bucket[num - min]){
res.add(num);
bucket[num - min] = false;
}
}
}
int[] result = new int[res.size()];
for (int i = 0; i < res.size(); i++){
result[i] = res.get(i);
}
return result;
}
差距分析:其实不需要用map进行存储。用数组就可以存储了。最佳答案中存储方法是找出数组的最大值最小值,从而确定数组的最大范围。然后通过数值计算实现去重,并实现取数。