zoukankan      html  css  js  c++  java
  • 华为上机练习题--求两个数组的总和

    题目:

    求两个数组的和差:就是去掉两个数组中同样的元素 然后将两个数组中的元素存放在一个新的数组中,且数组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;
        }
    }



  • 相关阅读:
    SQL
    HTTP协议
    工具命令
    安全策略
    日志与审核
    python视频教程免费下载,百度云网盘资源,全套!
    《Python基础教程(第3版)》PDF电子版百度云网盘免费下载
    老男孩Python全栈开发视频教程全套完整版!免费分享!
    Pycharm激活码分享,2020最新Pycharm永久激活码~
    老男孩Python视频教程全套完整版!无偿分享~
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5132893.html
Copyright © 2011-2022 走看看