一个面试的排序题

本文提供了一种高效的方法来合并两个已排序的数组,并在合并过程中去除重复元素。通过两个示例方法实现这一目标:一种是直接合并并检查重复项,另一种是使用TreeMap进行去重。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

坛子里一个哥们的面试题:

         数组A与数组B均已排好序,用最有效率的办法将其合并成为数组C,要考虑到重复的数字将其去重

 

 

 

 

 

 

 

 

public class test {

	public static int[] b = { 1, 3, 5, 7, 9, 10, 11, 90 };
	public static int[] a = { 2, 5, 7, 8, 9 };
	public static void main(String[] args) {
		test1(a,b);

		Map<Integer,Integer> map=sortByTreeMap(a,b);
		Iterator iterator =  map.entrySet().iterator();
		while (iterator.hasNext()) {
           Map.Entry mapentry = (Map.Entry)iterator.next();
           System.out.print(mapentry.getValue()+" ");
		}

	}
	public static void test1(int[] a, int[] b){
		int[] c = new int[a.length + b.length];

		int i = 0, j = 0, k = 0;

		while (i < a.length && j < b.length) {
			if (a[i] <= b[j]) {
				if (a[i] == b[j]) {
					j++;
				} else {
					c[k] = a[i];
					i++;
					k++;
				}
			} else {
				c[k] = b[j];
				j++;
				k++;
			}
		}
		while (i < a.length) {
			c[k] = a[i];
			k++;
			i++;
		}
		while (j < b.length) {
			c[k] = b[j];
			j++;
			k++;
		}
		System.out.println(Arrays.toString(c));
	}
	public static Map sortByTreeMap(int[] a, int[] b){
		 Map<Integer,Integer> map=new TreeMap<Integer,Integer>();
	        for(int i=0;i<a.length;i++){
	            map.put(a[i], a[i]);
	        }
	        for(int i=0;i<b.length;i++){
	            map.put(b[i], b[i]);
	        }
	        return map;
	}

}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值