zoukankan      html  css  js  c++  java
  • 给定两个有序的整形数组,找出里边的相同元素

    题目:给定两个有序数组,需要找出两个数组中的相同元素?

    笨拙的解法,就是两层for循环嵌套,时间复杂度为 N 方。

    当时回答的解答,两个下标分别指向数组的头部,比如,i 指向数组 a 的头部,j 指向数组 b 的头部,那么比较 a[i] 和 b[j] ,如果 a[i] 较大,移动 j,如果 b[j] 较大,那么 移动 i,如果相等,那么 i 和 j 往后挪动,采用这种方式,只需要一次遍历即可,代码如下:

    public class FindCommon {
    
        public static List<Integer> getCommons(int[] a , int[] b){
            if( a.length <= 0 || b.length <= 0 ){//如果任何一个数组为空,那么就没有相同元素,边界判断
                return null;
            }
    
            List commons = new ArrayList<>();
            int i = 0,j=0;
            for (;i<a.length;i++){
                if( j >= b.length){
                    break;
                }
                //如果 a[i] 较大,那么就移动 j(前提:两个数组都是有序数组)
                while ( j < b.length-1 && a[i] > b[j]){
                    j++;
                }
    
                if(a[i] == b[j]){
                    commons.add(a[i]);
                    if( j < b.length ){
                        j++;
                    }
                }
            }
            return commons;
        }
    
        public static void main(String[] args) {
            int a[] = {1,1,1,1,3,5,6,8,9};
            int b[] = {1,1,3,5,7,10,12};
    
            List<Integer> result = getCommons(b,a);
            for (int i : result){
                System.out.print(i+",");
            }
        }
    }

    运行结果如下:

    细心的童鞋,可能会发现,当 a[i] > a[j] 的时候,我多加了一个判断: j < b.length - 1 ,为什么呢?是因为,如果是 j < b.length 时,这种情况下,j 已经到达了 b[] 的末尾,然而在末尾的时候,做了j++的运算,在下边的判断 a[i] == b[j] 的地方就会发生下标越界的情况,希望大家来纠错! 

    Read the fucking manual and source code
  • 相关阅读:
    Java IO流-NIO简介
    Java IO流-Properties
    Java IO流-序列化流和反序列化流
    Codeforces Round #371 (Div. 1) C
    bzoj 2326 矩阵快速幂
    IndiaHacks 2016
    HDU
    Educational Codeforces Round 51 (Rated for Div. 2) F
    Codeforces Round #345 (Div. 1) D
    Codeforces Round #300 E
  • 原文地址:https://www.cnblogs.com/qxynotebook/p/8808304.html
Copyright © 2011-2022 走看看