恒生面试过程中的一道笔试题,使用二分法计算任意整数在任意整数数组中的下标,不存在则返回-1。当时理了下思路,当时代码没有写完,后面回家后重新完成了这道题目,面试时的考虑并不全面,当然下面的代码水平也有待提升,欢迎大家指教。废话少说,上代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 题目:使用二分法计算任意整数在任意整数数组中的下标,不存在则返回-1
* @author xiaowei 2017年11月3日 下午2:12:38
*/
public class Dichotomy {
public static void main(String[] args) {
Dichotomy my = new Dichotomy();
int arr[] = { 1, 23, 5, 7, 9, 76, 8, 0, 4, 5, 7, 1, 8, 3, 8, 6 };
System.out.print("输入数组:");
for (int i : arr) {
System.out.print(i + "、");
}
System.out.println();
System.out.println(my.checkExist(76, arr));
}
/**
* 使用二分法计算任意整数在任意整数数组中的下标,不存在则返回-1
*/
public int checkExist(int i, int arr[]) {
// 数组为空
if (arr == null || arr.length == 0) {
return -1;
}
// 保存key-value的内部类
class Temp {
public int key;
public int value;
public Temp(int key, int value) {
this.key = key;
this.value = value;
}
}
// 将数组转为Temp的list
List<Temp> tl = new ArrayList<Temp>();
Temp temp;
for (int n = 0; n < arr.length; n++) {
temp = new Temp(n, arr[n]);
tl.add(temp);
}
// 冒泡排序-顺序
int len = tl.size();
for (int n = 0; n < len; n++) {
for (int m = len - 2; m >= n; m--) {
if (tl.get(m).value > tl.get(m + 1).value) {
temp = tl.get(m);
tl.set(m, tl.get(m + 1));
tl.set(m + 1, temp);
}
// System.out.print("第" + n + "、" + m + "次排序:");
// tl.forEach(t -> {
// System.out.print(t.value + "、");
// });
// System.out.println();
}
}
// System.out.print("排序结果:");
// tl.forEach(t -> {
// System.out.print(t.value + "、");
// });
// System.out.println();
// 查找排序后的第一个相同元素的位置
int mid;
while (true) {
// System.out.print("循环输出:");
// tl.forEach(t -> {
// System.out.print(t.value + "、");
// });
// System.out.println();
mid = len / 2;
temp = tl.get(mid);
// 若只剩下一个元素,则判断是否与i相等,并返回对应结果。
if (mid != 0) {
// 相等返回下标
if (temp.value != i) {
// 选出可能包含i的子list
tl = temp.value > i ? tl.subList(0, mid) : tl.subList(mid, len);
if ((len = tl.size()) == 0) {
return -1;
}
continue;
}
return temp.key;
}
return temp.value == i ? temp.key : -1;
}
}
}