華為上機練習題--求兩個數組的總和

來源:互聯網
上載者:User

標籤: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;
    }
}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.