标签:lse oid span std return str sea style modify
question:
Modify binary search so that it always returns the element with the smallest index that mathes the search element (and still guarantees logarithmic running time).
answer:
//注意二分查找一定要是有序数组!!!(我搞忘记了,然后怎么都查不出错QAQ)
import edu.princeton.cs.algs4.*; public class BinarySearch { public static int Rank(int key, int[]a, int lo, int hi) { if(lo > hi) return -1; int mid = lo + (hi - lo)/2; if(a[mid] == key) { int min = Rank(key, a, lo, mid-1); if(min != -1) return min; return mid; } else if(a[mid] > key) return Rank(key, a, lo, mid-1); else return Rank(key, a, mid+1, hi); } public static void main(String[] args) { int a[] = {0,0,1,1,2,4,5,5,6,8,9,10};//二分查找必须是有序数组!!! int key = 1; int ans = Rank(key,a,0,a.length-1); StdOut.println(ans); } }
标签:lse oid span std return str sea style modify
原文地址:https://www.cnblogs.com/w-j-c/p/9128715.html