已知A,B和C为3个递增有序的顺序表,编写算法,实现删除A表中既在B表中出现,又在C表中出现的所有元素。

该博客介绍了一个Java程序,用于从三个递增有序的整数数组A、B和C中移除公共元素。算法首先遍历数组A,当遇到的元素在B中时,再检查是否也在C中,如果不在C中则保留,同时更新当前A中保留元素的位置。最终,A数组中将只保留非公共元素,且仍保持递增有序。
摘要由CSDN通过智能技术生成

时间复杂度O(n),空间复杂度O(1);

package sequenceList;

public class RemoveThePublicElement {
    public static void main(String[] args) {
        Integer[] A = {1, 2, 3, 4, 5, 6, 6, 7};
        Integer[] B = {2, 4, 6, 7, 9};
        Integer[] C = {1, 2, 2, 6, 8, 10};
        RemoveThePublicElement.removeThePublicElement(A, B, C);
        for (Integer e : A) {
            System.out.println(e);
        }
    }

    /**
     * @param listA 递增有序的顺序表 A
     * @param listB 递增有序的顺序表 B
     * @param listC 递增有序的顺序表 C
     * @param <T>   递增有序的顺序表的元素类型
     * @return 返回最终经过处理的递增有序的顺序表A
     */
    public static <T extends Comparable> void removeThePublicElement(T[] listA, T[] listB, T[] listC) {
        if (listA.length==0){
            throw new RuntimeException("顺序表A为空");
        }
        int indexB = 0, indexC = 0;       //indexA,indexB,indexC为扫描顺序表A,B和C的工作变量
        int currentAIndex = -1;           //currentAIndex用于记录A表中保留下来的元素在A表中的位置
        for (int indexA = 0; indexA < listA.length && indexB < listB.length && indexC < listC.length; indexA++) {
            while (listA[indexA].compareTo(listB[indexB]) > 0) {
                indexB++;
            }
            if (listA[indexA].compareTo(listB[indexB]) == 0) {
                while (listA[indexA].compareTo(listC[indexC]) > 0) {
                    indexC++;
                }
                if (listA[indexA].compareTo(listC[indexC]) == 0) {
                    continue;
                } else {
                    currentAIndex++;
                }
            } else {
                currentAIndex++;
            }
            listA[currentAIndex] = listA[indexA];
        }
        for (int i = currentAIndex + 1; i < listA.length; i++) {
            listA[i] = null;
        }
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值