349. Intersection of Two Arrays

问题链接:https://leetcode.com/problems/intersection-of-two-arrays/

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

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

Note:

  • Each element in the result must be unique.
  • The result can be in any order.
思路:判断一个数是否在数组里,而不在交集的缓存数组里
问题:对于两个数组的非零元素的交集可以正常显示,但是若交集中含有0元素,则零元素无法呈现。
原因:数组在初始化时默认元素值均为0,所以再判断是否在缓存数组中时总是为true,导致0元素无法加入到缓存数组中。
解决办法:将缓存数组用-1填充,可以提交到LeetCode中,但是若测试用例含有-1则又通不过
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        int len = Math.min(nums1.length, nums2.length);
        int[] temp = new int[len];
        Arrays.fill(temp, -1);
        int index = 0;
        
        for(int i=0;i<nums1.length;i++) {
            if(isNumInArray(nums2,nums1[i]) && !isNumInArray(temp,nums1[i])) {
                temp[index++] = nums1[i];
            }
        }
        
        return Arrays.copyOfRange(temp, 0, index);
    }
    
    private boolean isNumInArray(int[] nums, int num) {
        for(int i=0;i<nums.length;i++) {
            if(num == nums[i]) {
                return true;
            }
        }
        return false;
    }
}

可以换一个思路,用set等容器实现:http://blog.csdn.net/ruobing2011/article/details/51514405

不能有重复数字,就想到使用数据类型Set。 
逻辑原理: 

  • 数组一的数据存入hashset 
  • 遍历数组二如果set中存有该数据存入arraylist中,同时从set中remove该元素,防止多个元素重复 
  • 遍历list转变为array返回数据

public class Solution {  
    public int[] intersection(int[] nums1, int[] nums2) {  
        if(nums1==null || nums2==null)  
            return null;  
        if(nums1.length==0 || nums2.length==0)  
            return new int[0];  
  
        Set<Integer> set=new HashSet<Integer>();  
        for(int i=0;i<nums1.length;i++){  
            set.add(nums1[i]);  
        }  
  
        List<Integer> res = new ArrayList<Integer>();  
        for(int i=0;i<nums2.length;i++){  
            if(set.contains(nums2[i])){  
                res.add(nums2[i]);  
                set.remove(nums2[i]);//!!防止add到重复的数字  
            }  
        }  
        //遍历list成为数组返回  
        int[]a=new int[res.size()];  
        for(int i=0;i<res.size();i++){  
            a[i]=(int)res.get(i);  
        }  
  
        return a;  
    }  
}

感想:思维不要僵化,要掌握各容器的特点,并根据需求灵活选用,而不是看到返回类型为数组在内部就一定要用数组


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值