JAVA面试基础(代码之类)

来源:互联网 发布:ios原生网络请求封装 编辑:程序博客网 时间:2024/05/29 13:50

1、数组基本运算

class Test3 {//没有public照常运行public static void main(String[] args) {int a[] = new int[5];//System.out.println(a[5]);  //throw java.lang.ArrayIndexOutOfBoundsException 不是编译错误System.out.println(a[0]);  //输出0}}

2、输出字符串中只出现一次的第一个字符(例如:eileloiofmopq 输出:f)

public static void print(String str) {char c[] = str.toCharArray();boolean flag;for(int i=0; i<c.length; i++) {flag = true;for(int j=0; j<c.length; j++) {if(i != j && c[i] == c[j]) {flag = false;break;}}if(flag == true) {System.out.println("字符串" + str + "出现一次的字符是:" + c[i]);break;}}}

3、二分法查找(返回对应的下标,如果没有找到返回-1,并且传入的数组一定要是顺序排列的数组)

public int binarySearch(int key, int array[]) {int minIndex = 0;int maxIndex = array.length - 1;int midIndex = (minIndex + maxIndex)/2;while(key != array[midIndex]) {if(key > array[midIndex]) {minIndex = midIndex + 1;} else if(key < array[midIndex]) {maxIndex = midIndex - 1;} if(maxIndex < minIndex) {return -1;}midIndex = (minIndex + maxIndex)/2;}return midIndex;}


4、返回新数组,属于数组a但不属于数组b

public Object[] sub(Object a[], Object b[]) {List<Object> newObject = new ArrayList<Object>();boolean flag ;for(int i=0; i<a.length; i++) {flag = true;for(int j=0; j<b.length; j++) {if(a[i].equals(b[j])) {flag = false;break;}}if(flag == true) {newObject.add(a[i]);}}return newObject.toArray();}

5、计算:count(n)=1! + 2! + ▪▪▪▪▪▪ + n!;

publicint count(int n) {int result = 0;for(int i=1; i<=n; i++) {int tempResult = 1;for(int j=1; j<=i; j++) {tempResult *= j;}result += tempResult;}return result;}
以上纯属个人见解,有错误或者更好地方法,谢谢指正!

原创粉丝点击