您的位置:首页 > 其它

给定两个已排序序列,找出共同的元素

2017-07-12 23:25 176 查看
[java] view
plain copy

<pre name="code" class="java">package com.array;  

  

import java.util.ArrayList;  

import java.util.List;  

  

public class CommonItemInTwoSortedArray {  

    /** 

     * 题目:给定两个已排序序列,找出共同的元素。 1.定义两个指针分别指向序列的开始。 

     * 如果指向的两个元素相等,则找到一个相同的元素;如果不等,则将指向较小元素的指针向前移动。 重复执行上面的步骤,直到有一个指针指向序列尾端。 

     * 2.如果数组大小差得很多,就遍历小的,然后在大的里二分查找 

     */  

  

    public static void main(String[] args) {  

        int[] a = { 1, 3, 5, 7 };  

        int[] b = { 2, 3, 4, 5, 6, 8 };  

        List<Integer> c = findCommon(a, b);  

        for (int each : c) {  

            System.out.print(each + " ");  

        }  

    }  

    public static List<Integer> findCommon(int[] a,int[] b){  

        List<Integer> commList = new ArrayList<Integer>();  

        if(!(a!=null&&a.length>0&&b!=null&&b.length>0)){  

            return commList;  

        }  

        int lenA = a.length;  

        int lenB = b.length;  

        for(int i = 0 ,j = 0;i<lenA&&j<lenB;){  

            if(a[i]>b[j]){  

                j++;//是己经排好序的序列  

            }else if(a[i]<b[j]){  

                i++;  

            }else if(a[i]==b[j]){  

                commList.add(a[i]);  

                i++;  

                j++;  

            }  

        }  

        return commList;  

    }  

}  

转载自:http://blog.csdn.net/zjcheer_up/article/details/38339183
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐