有两个整形数组,int[]a={10,20,30,40,50},int[] b={10,20,60},编写代码实现把a,b中不同的部分提取 
出来,得到int[] c={30,40,50,60}.

解决方案 »

  1.   

    回完那个帖子之后,看到这个,哎,我在复制一遍吧结贴率0.00%。Christ!
    public class FindDifference {
    static int count1 = 0;
    static int count2 = 0;

    public static void main(String args[]){
    int[] source1 = new int[]{10, 20, 30, 40, 60};
    int[] source2 = new int[]{20, 25, 37, 60, 70};

    int[] difference = new int[source1.length + source2.length];
    int[] same = new int[source1.length];

    for (int i=0; i<source1.length; i++){
    for (int j=0; j<source2.length; j++){
    if (source1[i] == source2[j]){
    same[count2] = source1[i];
    source2[j] = -1; //这个地方你要注意,我是把-1作为标识位的,也就是说第二个数组里面没有-1这个元素,否则就会出错;
    count2 ++;
    break;
    }
    if (j == source2.length -1){
    difference[count1] = source1[i];
    count1 ++;
    }
    }
    }

    for(int i=0; i<source2.length; i++){
    if (source2[i] != -1){
    difference[count1] = source2[i];
    count1 ++;
    }
    }

    System.out.print("Different elements: ");
    for (int i=0; i<count1; i++)
    System.out.print(difference[i] +", ");

    System.out.print("\nSame elements: ");
    for (int i=0; i<count2; i++)
    System.out.print(same[i] +", ");
    }
    }
    结果:
    Different elements: 10, 30, 40, 25, 37, 70, 
    Same elements: 20, 60, 
    import java.util.*;public class FindDifferent {
    public static void main(String args[]){
    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

    int[] source1 = new int[]{10, 20, 30, 40, 60};
    int[] source2 = new int[]{20, 25, 37, 60, 70};

    for (int i=0; i<source1.length; i++)
    map.put(source1[i], 0);

    for (int i=0; i<source2.length; i++){
    if (map.containsKey(source2[i])){
    map.remove(source2[i]);
    map.put(source2[i], 1);
    }
    else{
    map.put(source2[i], 0);
    }
    } System.out.print(map.toString());
    }
    }
    结果:
    {70=0, 20=1, 37=0, 25=0, 40=0, 10=0, 60=1, 30=0}