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

    Intersection of Two Arrays

    1. Title

    349. Intersection of Two Arrays

    2. Http address

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

    3. The question

    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.

    4 My code(AC)

    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
           
            
            int [] empty = new int[0];
            if( nums1 == null || nums2 == null)
                return empty;
            int len1 = nums1.length;
            int len2 = nums2.length;
            if( len1 <=0 || len2 <=0)
                return empty;
            int [] result = new int[Math.min(len1, len2)];
            int [] re;
            int bf = Integer.MAX_VALUE;
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int i = 0, j = 0,curI = 0;
            while( i < len1 && j < len2)
            {
                if( nums1[i] == nums2[j])
                {
                    if( nums1[i] != bf) 
                        {
                            result[curI++] = nums1[i];
                            bf = nums1[i];
                        }
                    i++;
                    j++;
                }else if( nums1[i] < nums2[j]){
                    i++;
                }else{
                    j++;
                }
            }
            re = new int[curI];
            System.arraycopy(result, 0, re, 0, curI);
            return re;
        
        }
    }
    View Code
  • 相关阅读:
    Mina Core 10-执行器过滤器
    Mina Core 09-编解码过滤器
    Mina Core 08-IoBuffer
    Mina Basics 07-处理程序Handler
    Mina Basics 06-传输
    Mina Basics 05-过滤器
    Mina Basics 04- 会话
    Mina Basics 03-IoService
    Mina Basics 02-基础
    Mina Basics 01- 入门
  • 原文地址:https://www.cnblogs.com/ordili/p/5509354.html
Copyright © 2011-2022 走看看