LeetCode Intersetion of two array

来源:互联网 发布:李涛疯狂淘宝 传销 编辑:程序博客网 时间:2024/06/05 12:41

description:

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.

解题思路: 使用排序算法然后再进行处理,注意当比较两个数组相等的时候,要排除相同的数据的情况,也就是一个选代表的过程,当两个数字是相等时也要注意同时将数组的下表加一。

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        if (nums1 == null || nums2 == null) {            return null;        }        Arrays.sort(nums1);        Arrays.sort(nums2);        int[] arr = new int[Math.min(nums1.length, nums2.length)];        int i = 0, j = 0, index = 0;        while (i < nums1.length && j < nums2.length) {            if (nums1[i] == nums2[j]) {                if (index == 0 || arr[index - 1] != nums1[i]) {                    arr[index++] = nums1[i];                }                j++;                i++;            } else if (nums1[i] > nums2[j]) {                j++;            } else {                i++;            }        }        int[] result = new int[index];        for (int k = 0; k < index; k++) {            result[k] = arr[k];        }        return result;    }}
当然,这道题目也能够使用hashmap的方式进行求解,当所要的数据存在于map中的时候,数组添加这个数,反复这一过程直到求解出所用的数据。
0 0
原创粉丝点击