亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【leetcode75】Intersection of Two Arrays(數組的交集)

题目描述:
给定两个数组求他们的公共部分,输出形式是数组,相同的元素只是输出一次
例如:

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

原文描述:

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.

思路一:
  • 使用HashMap<Integer,Boolean>数据结构,首先是便利Array1,放入map1
  • 遍历Array2,判断map1是否包含,并且和前一个不相同,存入map2
  • 取出map2的数据,存入数组输出‘
代码:
public class Solution {
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        HashMap<Integer, Boolean> map1 = new HashMap<Integer, Boolean>();
        HashMap<Integer, Boolean> intersectMap = new HashMap<Integer, Boolean>();
        for (int i = 0; i < nums1.length; i++) {
            if (!map1.containsKey(nums1[i])) {
                map1.put(nums1[i], true);
            }
        }
        for (int j = 0; j < nums2.length; j++) {
            if (map1.containsKey(nums2[j]) && !intersectMap.containsKey(nums2[j])) {
                intersectMap.put(nums2[j], true);
            }
        }
        int[] result = new int[intersectMap.size()];
        int i = 0;
        for (Integer e : intersectMap.keySet()) {
            result[i] = e;
            i++;
        }
        return result;
    }
}
思路二:
  • 先把两个数组排序
  • 索引i,j分别代表Array1和Array2,相等都加1,谁小谁对应的索引加1
代码:
public class Solution {
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int i = 0, j = 0;
        int[] temp = new int[nums1.length];
        int index = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] == nums2[j]) {
                if (index == 0  temp[index - 1] != nums1[i]) {
                    temp[index++] = nums1[i];
                }
                i++;
                j++;
            } else if (nums1[i] < nums2[j]) {
                i++;
            } else {
                j++;
            }
        }

        int[] result = new int[index];
        for (int k = 0; k < index; k++) {
            result[k] = temp[k];
        }

        return result;
    }
}
更多leetcode题目,请看我的leetcode专栏。:
點擊查看更多內容
8人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
移動開發工程師
手記
粉絲
424
獲贊與收藏
5663

關注作者,訂閱最新文章

閱讀免費教程

感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消