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
  • 相关阅读:
    使用jquery.validate.js实现boostrap3的校验和验证
    MySQL 随机取数据效率问题
    qq在线客服代码
    使用Shell脚本查找程序对应的进程ID,并杀死进程
    Redis-概述
    JVM的类加载机制
    volatile
    java内存相关
    设计模式--模板方法
    设计模式概述
  • 原文地址:https://www.cnblogs.com/ordili/p/5509354.html
Copyright © 2011-2022 走看看