您的位置:首页 > 编程语言 > Java开发

Java编程题目-11:数组的交集

2016-09-18 22:42 381 查看
奉上LeetCode题目地址:请戳这里

题目要求如下:

Given two arrays, write a function to compute their intersection.

Example:

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:

Each element in the result should appear as many times as it shows in both arrays.

The result can be in any order.

Follow up:

What if the given array is already sorted? How would you optimize your algorithm?

What if nums1’s size is small compared to nums2’s size? Which algorithm is better?

What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

写了好一会儿才考虑周全,代码如下:

public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int len1 = nums1.length;
int len2 = nums2.length;
int minLen = len1 > len2 ? len2 : len1;

if(len1==0 || len2 ==0) return new int[]{};// 数组有一个为空时直接返回空数组
if(arrayIsEqual(nums1, nums2)) return nums1;// 数组相同时直接返回任一个
if (nums1[len1 - 1] < nums2[0]) return new int[] {};// 由于数组有序,数组1的最大值小于数组2的最小值时直接返回空数组

ArrayList<Integer> list1 = arrayToList(nums1);
ArrayList<Integer> list2 = arrayToList(nums2);

int[] numbers;
if (minLen == nums1.length) {
numbers = nums1;
} else {
numbers = nums2;
}
ArrayList<Integer> resList = new ArrayList<Integer>();
for (int i = 0; i < minLen; i++) {
if (list1.contains(numbers[i]) && list2.contains(numbers[i])) {
resList.add(numbers[i]);
list1.remove(getIndex(list1, numbers[i]));// 为了避免重复,找到一个交集元素后直接在list中删除
list2.remove(getIndex(list2, numbers[i]));
}
}
int[] res = new int[resList.size()];
for(int m =0 ;m<resList.size();m++){
res[m] = resList.get(m);
}
return res;
}
// 获取数组元素的index
public int getIndex(ArrayList<Integer> nums,int target){
int res = 0;
for(int i=0;i<nums.size();i++){
if(nums.get(i) == target){
res = i;
break;
}
}
return res;
}
// 将数组转换成List
public ArrayList<Integer> arrayToList(int[] nums){
ArrayList<Integer> list = new ArrayList<Integer>();
for (int num : nums) {
list.add(num);
}
return list;
}
// 判断两个数组是否相同
public boolean arrayIsEqual(int[] nums1,int[] nums2){
boolean isEquals = false;
if(nums1.length==nums2.length){
for(int i = 0;i<nums1.length;i++){
if(nums1[i]!=nums2[i]){
isEquals=false;
break;
}else{
isEquals = true;
continue;
}
}
}
return isEquals;
}
}


代码写起来没什么难度,对于我来说就是要在不运行情况下考虑周全比较难。以下三点就没考虑到:

1. 两个数组同时为空数组的情况没考虑到

2. 两个数组相同的情况也么考虑到

3. 找到一个交集元素后,要在List中删除掉,不然会出现错误交集

动手写起代码来不难,难的是考虑周全
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 编程