zoukankan      html  css  js  c++  java
  • java数组的交集和并集

    前两天给我出了一道题,求数组的并集和交集,然后我试着写一下,很尴尬,由于长时间没有写过代码,一开始数组是如何定义的给忘了。当时我说了我的思路,不过也是很low的做法,查阅网上的一些资料,实现的很厉害,不过对于我这种习惯了看1+1=2这种操作的人,难免有些为难。
    好了,牢骚发够了,这里提供一种思路,在我看来,很简单。

    public class SumandRetain {
    	Set<Integer> m=new HashSet<>();
    	ArrayList<Integer> a1=new ArrayList<>();
    	ArrayList<Integer> b1=new ArrayList<>();
    //求两个数组的并集(利用Set的去重机制)
    	public  Set<Integer> sum(int a[],int b[]) {
    		for(int i=0;i<a.length;i++) {
    			m.add(a[i]);
    		}
    		for(int j=0;j<b.length;j++) {
    			m.add(b[j]);
    		}	
    		return m;
    	}
    //求两个数组的交集(利用集合类的retainAll()方法)	
    	public ArrayList<Integer> retain(int a[],int b[]){
    	
    		for(int i=0;i<a.length;i++) {
    			a1.add(a[i]);
    		}
    		for(int j=0;j<b.length;j++) {
    			b1.add(b[j]);
    		}
    		b1.retainAll(a1);
    		return b1;	
    	}
    }
    

    再编写主方法

    public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		int a[]= {1,3,5,7};
    		int b[]= {2,3,4,9};
    		SumandRetain sumandReatain=new SumandRetain();
    		System.out.println(sumandReatain.sum( a,b));
    		System.out.println(sumandReatain.retain(a, b));
    
    	}
    
  • 相关阅读:
    linux 下vi中关于删除某段,某行,或者全部删除的命令
    Crontab的格式
    Crontab的格式
    Eclipse验证码
    jetty插件配置(开发)
    MongoDB使用手册
    Docker学习笔记(1) — docker 常用命令
    debian网易163更新服务器 源
    ssh安装过程
    HTML——列表标签
  • 原文地址:https://www.cnblogs.com/dearnotes/p/13088472.html
Copyright © 2011-2022 走看看