Java-合并两个没有重复的数组(不允许使用库) [英] Java - Merge Two Arrays without Duplicates (No libraries allowed)

查看:79
本文介绍了Java-合并两个没有重复的数组(不允许使用库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要有关编程问题的帮助.

Need assistance with programming issue.

必须使用Java.无法使用任何库(Arraylist等).

Must be in Java. Cannot use any libraries (Arraylist, etc.).

int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0}
int[] b = {0, 2, 11, 12, 5, 6, 8}

必须创建一个引用这两个数组的对象,该对象将两个数组合并在一起,删除重复的数组并对其进行排序.

Have to create an object referencing these two arrays in a method that merges them together, removes duplicates, and sorts them.

到目前为止,这是我的排序.难以合并两个数组并删除重复项.

Here's my sort so far. Having difficulty combining two arrays and removing duplicates though.

int lastPos;
int index;
int temp;

for(lastPos = a.length - 1; lastPos >= 0; lastPos--) {
    for(index = 0; index <= lastPos - 1; index++) {
        if(a[index] > a[index+1]) {
            temp = a[index];
            a[index] = a[index+1];
            a[index+1] = temp;
        }
    }
}

推荐答案

合并两个没有重复的数组并对其进行排序(不使用任何库). 使用对象.

Merge Two Arrays without Duplicates and Sort it (No libraries used). Using an object.

public class MergeRemoveDupSort {    

public int[] mergeRemoveDupSortIt(int[] a, int[] b) {   
    int [] c = mergeIt(a,b);
    int [] d = removeIt(c);
    int [] e = sortIt(d);
    return e;
}

private int[] mergeIt(int[] a, int[] b) {   
    int[] c = new int[a.length + b.length];        
    int k=0;
    for (int n : a) c[k++]=n;        
    for (int n : b) c[k++]=n;   
    return c;
}

private int[] removeIt(int[] c) {  
    int len=c.length;
    for (int i=0;i<len-1;i++) 
        for (int j=i+1;j<len;j++)
            if (c[i] == c[j]) {
                for (int k=j;k<len-1;k++)
                    c[k]=c[k+1];
                --len;
            } 
    int [] r = new int[len];
    for (int i=0;i<r.length;i++)
        r[i]=c[i];
    return r;
}

private int[] sortIt(int[] a) {   
    for(int index=0; index<a.length-1; index++)
       for(int i=index+1; i<a.length; i++)
           if(a[index] > a[i]){
               int temp = a[index];
               a[index] = a[i];
               a[i] = temp;
           }
     return a;
}    

public void printIt(int[] a) {   
    System.out.print("[");
    for (int i=0;i<a.length;i++){
        System.out.print(a[i]);
        if (i!=a.length-1) System.out.print(",");
        else System.out.print("]");            
    }        
}

public static void main(String[] args) {
    int[] a = {1, 2, 3, 4, 8, 5, 7, 9, 6, 0};
    int[] b = {0, 2, 11, 12, 5, 6, 8};

    MergeRemoveDupSort array = new MergeRemoveDupSort();
    int [] r = array.mergeRemoveDupSortIt(a, b);
    array.printIt(r);        
}        
}

这篇关于Java-合并两个没有重复的数组(不允许使用库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆