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

来源:互联网 发布:软件参数 编辑:程序博客网 时间:2024/06/06 17:49
[java] view plain copy
  1. <pre name="code" class="java">package com.array;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. public class CommonItemInTwoSortedArray {  
  7.     /** 
  8.      * 题目:给定两个已排序序列,找出共同的元素。 1.定义两个指针分别指向序列的开始。 
  9.      * 如果指向的两个元素相等,则找到一个相同的元素;如果不等,则将指向较小元素的指针向前移动。 重复执行上面的步骤,直到有一个指针指向序列尾端。 
  10.      * 2.如果数组大小差得很多,就遍历小的,然后在大的里二分查找 
  11.      */  
  12.   
  13.     public static void main(String[] args) {  
  14.         int[] a = { 1357 };  
  15.         int[] b = { 234568 };  
  16.         List<Integer> c = findCommon(a, b);  
  17.         for (int each : c) {  
  18.             System.out.print(each + " ");  
  19.         }  
  20.     }  
  21.     public static List<Integer> findCommon(int[] a,int[] b){  
  22.         List<Integer> commList = new ArrayList<Integer>();  
  23.         if(!(a!=null&&a.length>0&&b!=null&&b.length>0)){  
  24.             return commList;  
  25.         }  
  26.         int lenA = a.length;  
  27.         int lenB = b.length;  
  28.         for(int i = 0 ,j = 0;i<lenA&&j<lenB;){  
  29.             if(a[i]>b[j]){  
  30.                 j++;//是己经排好序的序列  
  31.             }else if(a[i]<b[j]){  
  32.                 i++;  
  33.             }else if(a[i]==b[j]){  
  34.                 commList.add(a[i]);  
  35.                 i++;  
  36.                 j++;  
  37.             }  
  38.         }  
  39.         return commList;  
  40.     }  
  41. }  

转载自:http://blog.csdn.net/zjcheer_up/article/details/38339183
阅读全文
0 0
原创粉丝点击