收集面试题(十八)(数组拷贝)

// 有两个数组A,B,B数组中的元素包含在A数组中,
// 请写一段代码把A数组中B没有的元素放到C数组中。
// 假如数组中都是数字,而且已经按大小排序,请写一段代码最快效率把
// 上面的元素放到C数组中。

/**
 * The Class CopyArray.
 */
public class CopyArray {

	/**
	 * The main method.
	 * 
	 * @param args
	 *            the arguments
	 */
	public static void main(String[] args) {
		copyNoSort();
		System.out.println("sort: ");
		copySort();
	}

	/**
	 * Copy no sort.
	 */
	// 循环进行m*n次
	public static void copyNoSort() {

		int[] arrayA = new int[] { 11, 1, 2, 13, 4, 5, 6, 7, 8, 9 };
		int[] arrayB = new int[] { 2, 4, 6, 8 };

		int[] arrayC = new int[arrayA.length - arrayB.length];
		int t = 0;
		for (int i = 0; i < arrayA.length; i++) {
			boolean isHave = true;
			for (int k = 0; k < arrayB.length; k++) {
				if (arrayA[i] == arrayB[k]) {
					isHave = false;
				}
			}

			if (isHave) {
				arrayC[t] = arrayA[i];
				t++;
			}
		}

		for (int i = 0; i < arrayC.length; i++) {
			System.out.print(arrayC[i] + ", ");
		}

	}

	/**
	 * Copy sort.
	 */
	public static void copySort() {
		int[] arrayA = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13 };
		int[] arrayB = new int[] { 2, 4, 6, 8 };

		int[] arrayC = new int[arrayA.length - arrayB.length];

		int k = 0;
		int t = 0;
		for (int i = 0; i < arrayA.length; i++) {

			if (k < arrayB.length) {
				if (arrayA[i] < arrayB[k]) {
					arrayC[t] = arrayA[i];
					t++;
				} else {
					k++;
				}
			} else {

				arrayC[t] = arrayA[i];
				t++;
			}
		}

		for (int i = 0; i < arrayC.length; i++) {
			System.out.print(arrayC[i] + ", ");
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值