排序

1. Intersection of Two Arrays

https://www.cnblogs.com/grandyang/p/5533305.html
思路一:对两数组进行排序,然后比较大小。比如相等,则加到set中;否则,让小的那一方指针后移。

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        Set<Integer> result= new HashSet<Integer>();
        int i=0;
        int j=0;
        while(i<nums1.length&&j<nums2.length){
            if(nums1[i] == nums2[j]){
                result.add(nums1[i]); 
                i++;
                j++;
            }
            else if(nums1[i]>nums2[j]){
                j++;
            }
            else if(nums1[i]<nums2[j]){
                i++;
            }
        }
        int[] res = new int[result.size()];
        Object[] ob = result.toArray();
        for(int y=0;y<result.size();y++){
            res[y]=(int)ob[y];
        }
        return res;
    }
}

思路2:利用map。把数组1放到map中,然后遍历数组2,如果元素在map中,则加入到结果集里。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容