【算法学习】求两数组求差数(Java,三重境界)

来源:互联网 发布:淘宝销量怎么查看 编辑:程序博客网 时间:2024/06/16 01:37

【题目描述】:两个数组,一个A数组200个,,另一个B数组199个,两个数组乱序,但是差一个数,,,找出差的是那个数。



一。境界1(60分)

【1】遍历A数组,对每个数执行【2】操作
【2】遍历B数组对比是否存在此数。

参考代码如下:

/** * Created by zsl on 2017/8/20. */public class Main {    public static void main(String[] args) {        int arrayA[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11};        int arrayB[] = {1, 2, 3, 4, 5, 6, 7, 9, 11};//相差8        int a = 0;        boolean result = false;        for (int i = 0; i < arrayA.length; i++) {            a = arrayA[i];            result = false;            for (int j = 0; j < arrayB.length; j++) {   //遍历查找                if (arrayB[j] == a) {                    result = true;                    break;                }            }            if (!result) {                System.out.println(a);            }        }    }}



二。境界2(80分)

【1】利用数字原理,对第一个数组求和,
【2】对第二个数组求和
【3】求差即所求数。

参考代码如下:

public class Main {    public static void main(String[] args) {        int arrayA[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11};        int arrayB[] = {1, 2, 3, 4, 5, 6, 7, 9, 11};//相差8        int sumA = 0;        int sumB = 0;        for (int i = 0; i < arrayA.length; i++)             sumA += arrayA[i];//求和        for (int j = 0; j < arrayB.length; j++)            sumB += arrayB[j];//求和        System.out.println(sumA - sumB);//求差    }}



三。境界3(100分)

【1】利用位操作中的“异或”,
【2】两个相同的数求异或结果为0,0和任何数求异或为任何数本身
【3】用0和A数组及B数组求异或

参考代码如下:

public class Main {    public static void main(String[] args) {        int arrayA[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11};        int arrayB[] = {1, 2, 3, 4, 5, 6, 7, 9, 11};//相差8        int result = 0;        for (int i = 0; i < arrayA.length; i++)            result ^= arrayA[i];//求异或        for (int j = 0; j < arrayB.length; j++)            result ^= arrayB[j];//求异或        System.out.println(result);    }}

神器的算法,,还是6。。

原创粉丝点击