Leetcode——350. Intersection of Two Arrays II

题目原址

https://leetcode.com/problems/intersection-of-two-arrays-ii/description/

题目描述

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.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

解题思路

想要找两个数组中相等的元素,将相等的元素放在数组中返回。这个题有很多个解法。我说一下我刚刚AC的代码。可能不是最优解,但是是自己做出来的!
主要的思路就是,将一个数组放在ArrayList中,然后通过迭代器一点点遍历寻找跟另个数组相同的元素,如果找到相同,就移除相同的元素。

  • 定义需要的变量:
    • length是两个数组中元素个数多的元素个数。这个值用来初始化返回数组的个数。
    • j用来作为返回数组result的下标
    • array 是Array类型的变量,用来存储已知的一个数组的所有元素。
  • 利用ArrayList存储其中一个数组,我这里存储的是nums1
  • 定义迭代器,用来遍历array 中的元素,循环的条件是i<nums2.length,即将另一个没存储的数组nums2从头遍历,没拿到一个nums2中的一个元素,就从迭代器中找是否有一样的,如果有一样的,就将其移除,并结束本次内层循环,结束条件是定义一个flag来判断是否找到元素。如果没有一样的就遍历到迭代器结束。
  • 迭代器在每个外层循环中,都要指定回到初始位置。
  • 这里面还有有一个count变量,用来记录找到了多少个nums2中的元素,防止nums2中的元素都找到了,还继续遍历。

AC代码

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int length1 = nums1.length;
        int length2 = nums2.length;
        int length = length1 > length2 ? length1 : length2;
        int count = length2;
        int[] result = new int[length];
        int j = 0;
        boolean flag = false;
        List<Integer> array = new ArrayList<Integer>();
        for(int i: nums1) {
            array.add(i);
        }

        Iterator iterator = array.listIterator(0);
        for(int i = 0; i< nums2.length; i++) {
            flag = false;
            iterator = array.listIterator(0);
            while(flag == false && iterator.hasNext()) {
                if(count == 0)
                    break;
                if((Integer)iterator.next() == nums2[i]) {
                    result[j ++] = nums2[i];
                    flag = true;
                count--;
                    iterator.remove();
                }
            }
        }
        result = Arrays.copyOf(result, j);

        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值