有方法和arr已经排序......
public int search(ArrayList<Integer> arr, int numberToBeSearched) {
//Code here
return //insertion point
}
让我们成为{1,4,7}和numberToBeSearched 2。 return将为1,因为为了维持订单,它将介于1和4之间。
如果不使用Collections.binarySearch,你们怎么会在arr里面获得numberToBeSearched的插入点?
插入点是索引位置所在 该数字需要插入数组列表中,以便维护排序顺序。
答案 0 :(得分:0)
public int search(ArrayList<Integer> arr, int numberToBeSearched) {
int i=0;
for (i = 0; i < size(); i++) {
// if the element you are looking at is smaller than numberToBeSearched,
// go to the next element
if (arr.get(i) < numberToBeSearched) continue;
// if the element equals numberToBeSearched, return, because we don't duplicates
if (arr.get(i) == numberToBeSearched) return -1;
// otherwise, we have found the location of numberToBeSearched
return i;
}
// we looked through all of the elements, and they were all
// smaller than numberToBeSearched, so the index is end of the list
return i;
}