zoukankan      html  css  js  c++  java
  • 基于二分查找的两个数组求合集

          吾十有五而志于学,三十而立,四十而不惑,五十而知天命,六十而耳顺,七十而从心所欲不逾矩

                                              ---- 论语

      一个非常简单的例子,听到有人在说这个,就写下来玩玩。

    package test;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class Demo2 {
        
        public static List<Integer> intersection(int[] arr1, int[] arr2){
            List<Integer> list = new ArrayList<Integer>();
            for(int i : arr1){
                if(binarySearch(arr2, i))
                    list.add(i);
            }
            return list;
        }
        
        public static boolean binarySearch(int[] i, int j){
            Arrays.sort(i);
            int low = 0;
            int high = i.length - 1;
            
            while(high >= low && low <= i.length - 1 && high <= i.length - 1){
                int middle = low + ((high - low) >> 1);
                if(j == i[middle]){
                    return true;
                }else if(j > i[middle]){
                    low = middle + 1;
                }else{
                    high = middle - 1;
                }
            }
            return false;
        }
        
        public static void main(String[] args) {
            int[] arr1 = {1,2,4,5,6,7,11,34,56,55};
            int[] arr2 = {6,7,11,4,35,9,0,44};
            
            List<Integer> list = intersection(arr1, arr2);
            
            for(int i : list)
                System.out.print(i + ",");
            
        }
    
    }
  • 相关阅读:
    第一次练习总结
    第一次上机总结
    写在程序组干活之前
    虚拟机Centos7安装Mysql
    第一章 开发体验
    如何优雅的移植JavaScript组件到Blazor
    Asp.net core中RedisMQ的简单应用
    docker容器安装mysql
    Centos 8安装Docker
    c# 定时启动一个操作、任务(版本2)
  • 原文地址:https://www.cnblogs.com/hankedang/p/4372755.html
Copyright © 2011-2022 走看看