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

xiaoxiao2023-03-20  48

// 有两个数组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] + ", "); } } }

 

转载请注明原文地址: https://www.6miu.com/read-4986784.html

最新回复(0)