设计模式_28
1. 有过一次失败的单元测试经验:好不容易申请到了2周的预研时间,我开开心心地研究怎么把JUnit引入项目,刚开始了两天,新的开发任务打断了我的计划,然后就再也没有继续了。。。
2.
代码:
/**
* 查找递增数组中第一个大于等于某个给定值的元素
* @return -1: 未找到
*/
public int findFirstEqualOrLargerIndex(int[] array, int num) {
if (array == null || array.length == 0) return -1;
int start = 0;
int end = array.length - 1;
while (start != end) {
int middle = start + (end - start) / 2;
if (array[middle] >= num) {
if (start == middle) return middle;
else
if (array[middle - 1] < num) return middle;
else end = middle -1;
} else {
start = middle + 1;
}
}
//start == end
if (array[start] >= num) {
return start;
} else {
return -1;
}
}
测试用例:
findFirstEqualOrLargerIndex(null, 1)
findFirstEqualOrLargerIndex(new int [0], 1)
findFirstEqualOrLargerIndex(new int [] {0}, 1)
findFirstEqualOrLargerIndex(new int [] {1}, 1)
findFirstEqualOrLargerIndex(new int [] {0, 0}, 1)
findFirstEqualOrLargerIndex(new int [] {0, 1}, 1)
findFirstEqualOrLargerIndex(new int [] {1, 1}, 1)
findFirstEqualOrLargerIndex(new int [] {0, 1, 2}, 1)
findFirstEqualOrLargerIndex(new int [] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 1)
findFirstEqualOrLargerIndex(new int [] {0, 1, 1, 1, 1, 1, 6, 7, 8, 9}, 1)
findFirstEqualOrLargerIndex(new int [] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 10)
我估计应该有漏洞,请老师和同学们指正~
展开