zoukankan      html  css  js  c++  java
  • LeetCode_350. Intersection of Two Arrays II

    350. Intersection of Two Arrays II

    Easy

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

    Example 1:

    Input: nums1 = [1,2,2,1], nums2 = [2,2]
    Output: [2,2]
    

    Example 2:

    Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    Output: [4,9]

    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?
    package leetcode.easy;
    
    public class IntersectionOfTwoArraysII {
    	private static void print_arr(int[] nums) {
    		for (int num : nums) {
    			System.out.print(num + " ");
    		}
    		System.out.println();
    	}
    
    	public int[] intersect(int[] nums1, int[] nums2) {
    		int i = 0, j = 0, k = 0;
    		int len = nums1.length < nums2.length ? nums1.length : nums2.length;
    		int[] nums = new int[len];
    		java.util.Arrays.sort(nums1);
    		java.util.Arrays.sort(nums2);
    		while (i < nums1.length && j < nums2.length) {
    			if (nums1[i] < nums2[j]) {
    				i++;
    			} else if (nums1[i] > nums2[j]) {
    				j++;
    			} else {
    				nums[k++] = nums1[i];
    				i++;
    				j++;
    			}
    		}
    		return java.util.Arrays.copyOf(nums, k);
    	}
    
    	@org.junit.Test
    	public void test1() {
    		int[] nums1 = { 1, 2, 2, 1 };
    		int[] nums2 = { 2, 2 };
    		print_arr(intersect(nums1, nums2));
    	}
    
    	@org.junit.Test
    	public void test2() {
    		int[] nums1 = { 4, 9, 5 };
    		int[] nums2 = { 9, 4, 9, 8, 4 };
    		print_arr(intersect(nums1, nums2));
    	}
    }
    
  • 相关阅读:
    第3章 神经网络
    OpenCV基础(一)---图像卷积运算
    OpenCV-自定义harris检测
    C++类型转换
    剑指offer之【二叉搜索树与双向链表】
    剑指offer之【复杂链表的复制】
    剑指offer之【二叉树中和为某一值的路径】
    剑指offer之【二叉搜索树的后序遍历序列】
    剑指offer之【从上往下打印二叉树】
    剑指offer之【栈的压入、弹出序列】
  • 原文地址:https://www.cnblogs.com/denggelin/p/11842451.html
Copyright © 2011-2022 走看看