华为上机练习题--求两个数组的总和

来源:互联网 发布:报警回执Ps软件 编辑:程序博客网 时间:2024/06/05 06:12

题目:

求两个数组的和差:就是去掉两个数组中相同的元素 然后将两个数组中的元素存放在一个新的数组中,且数组A中元素要在B数组元素之前

 如:输入: int[] a={1,2,4,7,6,9};
                      int[] b={2,4,3,10};

         输出: int[] c = {1, 7, 6, 9, 3, 10};


分析: 剔除相同的元素要互相比较, 然后将不同的元素先后插入新的数组中, 所以我将重点放在比较上, 有可能效率有点低, 大家有什么好的想法可以分享下;


代码如下:

package com.wenj.test;

import java.util.ArrayList;
import java.util.List;

/*
* 求两个数组的和差:就是去掉两个数组中相同的元素 然后将两个数组中的元素存放在一个新的数组中
*  且数组A中元素要在B数组元素之前
*/

public class TestGetNewArr {

    public static void main(String args[]){
        int[] a={1,2,4,7,6,9};
        int[] b={2,4,3,10};
        int[] c;
        TestGetNewArr tg = new TestGetNewArr();
        c = tg.getNewArr(a, b);
        for(int i=0; i<c.length; i++){
            System.out.print(c[i] + " ");
        }
    }
    
    public int[] getNewArr(int[] a, int[] b){

        List<Integer> aL = new ArrayList<Integer>();
        for(int i=0; i<a.length; i++){//a与b的相比,相同的则不放进新的数组中
            boolean isExist = false;
            for(int j=0; j<b.length; j++){
                if(a[i] == b[j]){
                    isExist = true;
                }
            }
            if(!isExist){
                aL.add(a[i]);
            }
        }
        
        for(int i=0; i<b.length; i++){
            boolean isExist = false;
            for(int j=0; j<a.length; j++){
                if(b[i] == a[j]){
                    isExist = true;
                }
            }
            if(!isExist){
                aL.add(b[i]);
            }
        }
        
        int[] c = new int[aL.size()];
        for(int i=0; i<c.length; i++){
            c[i] = aL.get(i);
        }
        
        return c;
    }
}



0 0
原创粉丝点击