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

    这个题有收获啊。。。。

    前面不说了,MAP之后各遍历一次就行。

    SORT之后可以用2个PTR从最左边开始,能提前结束。

    排序之后的思路:
    遍历smaller array,看看每个元素在大的里面能不能找到,找的话返还位置,用的二分查找INDEX,找到直接在大的里面从头修改就行了。最后返还修改的部分。

    public class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            if(nums1.length == 0 || nums2.length == 0) return new int[0];
            
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            
            int[] small;
            int[] large;
            if(nums1.length < nums2.length){
                small = nums1;
                large = nums2;
            }else{
                small = nums2;
                large = nums1;
            }
            
    
            
            int left = 0;
            int right = 0;
    
    
            for(int i = 0; i < small.length; i++){
                int firstIndex = binarySearch(large,right,small[i]);
                if(firstIndex == -1) continue;
                else{
                    
                    large[left++] = large[firstIndex];
                    right = firstIndex+1;
                }
            }
            return Arrays.copyOf(large,left);
        }
        
        
        public int binarySearch(int[] nums, int start, int target){
            if(start >= nums.length) return -1;
            int l = start;
            int r = nums.length-1;
            while(l <= r){
                int M = nums[l] + (nums[r] - nums[l])/2;
                if(M < target) l++;
                else r--;
                    
                
            }
            //System.out.println(l);
            if(l >= 0 && l < nums.length && nums[l] == target) return l;
            else return -1;
        }
    }
    /*
    []
    []
    [1,2,3,4,5,6,5,44,5,6,7,5,5,4,3,3,2,3,4,5,5,6,7]
    [2,3,4,2,3,4,3,2,1,1,3,4,4,5,2,2,3,4,99]
    */
    

    还是挺有意思的。。

    有电面啦!!!!!!!!!!
    image
    加油啊!!!!

  • 相关阅读:
    jQuery右键菜单contextMenu使用实例
    如何调动员工的积极性 -引用LTP.Net知识库
    Linux 目录管理的相关命令
    linux bash基础特性
    Linux 文件系统简介(FHS:Filesystem Hierarchy Standard)
    Linux 基础命令
    docker 限制容器能够使用的资源
    docker 私有registry harbor安装
    docker Dockerfile里使用的命令说明
    docker 存储卷 Volumes
  • 原文地址:https://www.cnblogs.com/reboot329/p/5979390.html
Copyright © 2011-2022 走看看