2道面试题.

zc4444222000 2012-11-19 06:27:09
1.有2个数组A,B. B数组中元素包含在A数组中,请写一段代码把A数组中B没有的元素放到C数组中。

2.加入数组中都是数字,而且已经按大小排序,请写一段代码以最快效率把上一题的元素放到C数组中。
...全文
300 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
氧平台 2012-11-20
  • 打赏
  • 举报
回复
3,4 差点被绕进去了!
soton_dolphin 2012-11-20
  • 打赏
  • 举报
回复

import java.util.ArrayList;

public class TwoArrays {
	
	public static Object[] thirdArray(int[] a, int[] b){
		Object[] c = new Object[a.length];
		ArrayList<Integer> listB = new ArrayList<Integer>();
		ArrayList<Integer> listC = new ArrayList<Integer>();
		
		for (int i : b){
			listB.add(i);
		}
		
		for (int j=0;j<a.length;j++){
			if(!listB.contains((Integer)a[j])){
				listC.add(a[j]);
			}
		}
		return listC.toArray();
	}
	
	public static void main(String[] args){
		int[] first = {1,2,3,4,5,6};
		int[] second = {2,5,6};
		Object[] third = thirdArray(first, second);
		for(Object i : third){
			System.out.print(i + " ");
		}
	}
}
Candylibin 2012-11-20
  • 打赏
  • 举报
回复
public class TwoArrays {

	public static void main(String[] args) {

		int[] a = { 1, 2, 3, 4, 5, 6 };
        int[] b = { 2, 5, 6 };
        int[] c = new int[a.length - b.length];
        int l = 0;
        int k = 0;
 
        for (int i = 0; i < a.length; i++) {
            for (int j = k; j < b.length; j++) {
                if (a[i] == b[j]) {
                    k++;
                    break;
                } else if (a[i] < b[j]) {
                    c[l] = a[i];
                    l++;
                    break;
                }
            }
        }
        printArray(c);
		
	}
	
	public static void printArray(int[] arr){
			
			System.out.print("[");
			
			for(int a = 0;a<arr.length;a++){
				
				if(a!=arr.length-1)
					System.out.print(arr[a]+",");
				else
					System.out.println(arr[a]+"]");
		}
	}
}
baobao28 2012-11-20
  • 打赏
  • 举报
回复
不考虑楼主的第2个条件的话3楼代码写的很好,但是考虑到第2个条件的话就没有真正借用到第2个条件中“已经排序”,“B数组中元素包含在A数组中”这两个条件了,再就是更优化的效率问题

int[] a = { 1, 2, 3, 4, 5, 6 };
		int[] b = { 2, 5, 6 };
		int[] c = new int[a.length - b.length];
		int l = 0;
		int k = 0;

		for (int i = 0; i < a.length; i++) {
			for (int j = k; j < b.length; j++) {
				if (a[i] == b[j]) {
					k++;
					break;
				} else if (a[i] < b[j]) {
					c[l] = a[i];
					l++;
					break;
				}
			}
		}

		for (int s : c) {
			System.out.print(s);
		}
氧平台 2012-11-19
  • 打赏
  • 举报
回复
好像好绕啊! 明天有空帮你做!
蓝风遥遥 2012-11-19
  • 打赏
  • 举报
回复
public class A { public static void main(String[] args) { int[] a={2,1};int[] b={1,2,3,4}; int[] c=new int[b.length-a.length]; int x=0; for(int i=0;i<b.length;i++) { int flag=1; for(int j=0;j<a.length ;j++) { if(b[i]==a[j]) flag=0; } if(flag==1) { c[x]=b[i]; x++; } } for(int m=0;m<c.length;m++) System.out.println(c[m]); } }

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧