Intersection of Two Arrays II

来源:互联网 发布:淘宝退款申请客服介入 编辑:程序博客网 时间:2024/05/04 02:13

这道题的非排序做法值得自己再好好看看,尤其是while循环中的三个条件

非排序

public class Solution {    public int[] intersect(int[] nums1, int[] nums2) {int [] result = new int[0];if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {return result;}        List<Integer/*value*/> list = new LinkedList<>();Map<Integer/*value*/,Integer/*number*/> map = new HashMap<>();for (int i: nums1) {if (map.containsKey(i)){map.put(i, map.get(i) + 1);} else {map.put(i, 1);}}for (int i: nums2) {if (map.containsKey(i) && map.get(i) > 0){list.add(i);map.put(i, map.get(i) - 1);}}result = new int[list.size()];int i = 0;for (int k: list) {result[i++] = k;}return result;    }}

排序的方法

public class Solution {    public int[] intersect(int[] nums1, int[] nums2) {int [] temp = new int[0];        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {            return temp;        }        Arrays.sort(nums1);        Arrays.sort(nums2);        int i = 0, j = 0, k = 0;        temp = new int[nums1.length];        while (i < nums1.length && j < nums2.length) {            //if (nums1[i] != nums2[j]) {            if (nums1[i] < nums2[j]) {                i++;            } else if (nums1[i] == nums2[j]) {                temp[k++] = nums1[i];                i++;                j++;            } else {                j++;            }        }        int[] result = new int[k];        for (int m = 0; m < k; m++) {            result[m] = temp[m];        }        return result;    }}


0 0