2道面试题.
1.有2个数组A,B. B数组中元素包含在A数组中,请写一段代码把A数组中B没有的元素放到C数组中。2.加入数组中都是数字,而且已经按大小排序,请写一段代码以最快效率把上一题的元素放到C数组中。 --------------------编程问答-------------------- 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]);
}
}
--------------------编程问答-------------------- 好像好绕啊!
明天有空帮你做! --------------------编程问答--------------------
--------------------编程问答-------------------- 不考虑楼主的第2个条件的话3楼代码写的很好,但是考虑到第2个条件的话就没有真正借用到第2个条件中“已经排序”,“B数组中元素包含在A数组中”这两个条件了,再就是更优化的效率问题
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 + " ");
}
}
}
--------------------编程问答--------------------
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);
}
public class TwoArrays {--------------------编程问答-------------------- 3,4
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]+"]");
}
}
}
差点被绕进去了!
补充:Java , Java SE