leetcode[Intersection of Two Arrays]

[Intersection of Two Arrays II]的解法也可以适用于这里,只不过对结果的处理一个是set一个是list

解法一:

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
    	//既然是求交集,那么结果集合中就没有重复元素,先用Set来存
    	HashSet<Integer> set = new HashSet<>();
    	Arrays.sort(nums1);
    	Arrays.sort(nums2);
    	int begin = 0;//begin用来定位nums2的数组,防止找重了
    	for(int i = 0; i < nums1.length; i++){
    		for(int j = begin; j < nums2.length; j++){
    			if(nums1[i] == nums2[j]){
    				set.add(nums1[i]);
    				begin++;//因为先将nums1和nums2排序了
    			}
    		}
    	}
    	/*Integer[] temp = set.toArray(new Integer[set.size()]);
    	int[] res = new int[](temp);*/
    	
    	//上面想要将set转换为int[]数组,但是涉及到一堆泛型,泛型与基本类型又矛盾,自己写
    	int[] res = new int[set.size()];//知道set的size就可以了
    	int put = 0;
    	for(int t : set){
    		res[put++] = t;
    	}
    	return res;
    }
}


解法二:

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        LinkedList<Integer> list = new LinkedList<>();
        for(int i = 0; i < nums1.length; i++){//List采用contains这个接口,先转换为list
        	list.add(nums1[i]);
        }
        HashSet<Integer> temp = new HashSet<>();//要去重,所以用set存
        
        for(int i = 0; i < nums2.length; i++){
        	if(list.contains(nums2[i])){
        		temp.add(nums2[i]);
        		//list.remove(nums2[i]);//原来nums1对应的list删除这个元素
        		list.remove(new Integer(nums2[i]));//这里有个重载,若remove参数是int,代表下标,integer才代表对象
        	}
        }
        
        int[] res = new int[temp.size()];
        int put = 0;
        for(int t : temp){
        	res[put++] = t;
        }
        return res;
    }
}

解法三(对解法一的优化,思路更清晰):

public class Solution {
	
	public int binarySearch(int[] nums, int x){
		int low = 0, high = nums.length - 1;
		int mid = (low + high) / 2;
		while(low <= high){
			
			mid = (low + high) / 2;//二分查找在循环体内要修改mid!!
			
			if(x == nums[mid]){
				return mid;
			}
			else if(x < nums[mid]){
				high = mid - 1;
			}
			else{
				low = mid + 1;
			}
			//System.out.println(low + " : " + high + "  " + x);
		}
		return -1;
	}
	
    public int[] intersection(int[] nums1, int[] nums2) {
    	//求交集:思路是查找nums2中和nums1中相同的元素,涉及到查找,那么就先排序,用二分查找
    	Arrays.sort(nums2);
    	
    	HashSet<Integer> set = new HashSet<>();
    	//从nums1中开始查找
    	for(int i = 0; i < nums1.length; i++){
    		if(binarySearch(nums2, nums1[i]) != -1){
    			set.add(nums1[i]);//找到就插入
    		}
    		//System.out.println("...");
    	}
    	
    	int[] res = new int[set.size()];
    	int put = 0;
    	for(int t : set){
    		res[put++] = t;
    	}
    	
    	return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值