leetcode修炼之路——350. Intersection of Two Arrays II

题目如下:

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

 

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

Note:

    • Each element in the result should appear as many times as it shows in both arrays.
    • The result can be in any order.

题目分析:根据题目来说,明显就是求两个数组之间的交集。

代码实现:

public static int[] intersect(int[] nums1, int[] nums2) {

        List<Integer> reslut = new ArrayList<>();

        Arrays.sort(nums1);// 先进行数组排序
        Arrays.sort(nums2);

        int position = 0;// 记录位置

        for (int i = 0; i < nums2.length; i++) {

            if (position == nums1.length) {// 终止条件:如果位置已经是最后一个了,终止
                break;
            }

            for (int j = position; j < nums1.length; j++) {
                if (position < nums1.length) {
                    if (nums2[i] == nums1[j]) {
                        position = j + 1;// 记录下当前相等的位置
                        reslut.add(nums2[i]);
                        break;
                    }
                }
            }
        }

        int[] resultNums = new int[reslut.size()];

        for (int i = 0; i < reslut.size(); i++) {
            resultNums[i] = reslut.get(i);
        }

        return resultNums;

    }

上面算法很简单,就是先对数组进行排序,然后遍历,记录相等时另一个数组的位置,然后放入list中。

posted @ 2016-08-16 22:59  风起云涌,勿忘本心  阅读(143)  评论(0编辑  收藏  举报