Java---合并两个递增有序的数组

Java—合并两个递增有序的数组,结果逆序且不包含重复元素

用的是数据结构思想做的

闲来无事做做小练习

/**
 * @Author shall潇
 * @Date 2021/2/23
 * @Description
 * 两个递增的数组合并,并删除重复元素,并逆序输出
 * 利用数据结构思想
 */
public class MergeAB {
    public static void main(String[] args) {
        int[] a = {2,3,4,7,9,11};
        int[] b = {1,3,4,5,10};
        int[] result = new int[a.length+b.length];
        int p=0;    //p指针->a数组
        int q=0;    //q指针->b数组
        int i=0;    //i指针->result数组
        while (p<a.length && q<b.length){   //只要a 或 b 走完就退出
            if(a[p]<b[q]){                  //如果a中的元素更小
                result[i] = a[p];           //将a中的元素赋值给result
                p++;                        //p指针后移
                i++;                        //i指针后移
            }else if(a[p]>b[q]){            //同理b中的元素若更小
                result[i] = b[q];
                q++;
                i++;
            }else {                         //相同情况下只赋值一次
                result[i] = a[p];
                p++;                        //p指针后移
                q++;                        //q指针后移
                i++;
            }
        }
        while (p<a.length){                 //若b扫描完,a还没扫描完,直接将a剩下的插入result
            result[i] = a[p];
            p++;
            i++;
        }
        while (q<b.length){                 //同理
            result[i] = b[q];
            q++;
            i++;
        }

        result = Arrays.copyOf(result,i);  //删除末尾为0的元素(不是a和b里面的元素)
        System.out.println(Arrays.toString(result));

        //二分法逆序
        int low = 0;
        int high = result.length-1;
        int center =(low+high)/2;
        while (low<center){
            int temp = result[high];
            result[high] = result[low];
            result[low] = temp;
            low++;
            high--;
        }
        System.out.println(Arrays.toString(result));

    }
}

猜你喜欢

转载自blog.csdn.net/qq_43288259/article/details/114002129