码迷,mamicode.com
首页 > 编程语言 > 详细

计算两个集合的交集数字(java)

时间:2014-06-17 00:22:18      阅读:360      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

循环判断2个数组

将相同的公共元素复制到新数组中即可

 1 2 
 3 import java.util.Arrays;
 4 
 5 public class count_same_number {
 6 
 7     public static  int[] join(int[] a,int[] b)
 8     {
 9         int count=0;
10         int new_target[]=new int[Math.max(a.length, b.length)];//新数组
11         int index=0;
12         for(int i=0;i<a.length;i++)
13         {
14             for(int j=0;j<b.length;j++)
15             {
16                 if(a[i]==b[j])
17                 {
18                     new_target[index++]=a[i];
19                     break;//如果遇到相同元素则保存并退出本次循环 就本例而言不加break要计算30次 加了break只计算16次
20                 }
21                 count++;
22             }
23         }
24         
25         System.out.println(Arrays.toString(new_target));
26         System.out.println("共计算"+count+"次");
27         return new_target;
28         
29     }
30     
31     
32     public static void main(String[] args) {
33         int a[]={1,2,3,4,5};
34         int b[]={2,4,92,3,28,32};
35         join(a,b);
36 
37     }
38 
39 }

 

运行效果:

bubuko.com,布布扣

 

 

计算两个集合的交集数字(java),布布扣,bubuko.com

计算两个集合的交集数字(java)

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/sweetculiji/p/3789992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!