0,1序列中找到第一个1出现的位置

/*
 * 从0,1数组中找到第一个1出现的位置
 * 1一旦出现,则以后全为1
 * 如:0011111
 */
public class FindFirstOne {
    //参数:数组a,低位low,高位a.length-1
    //返回第一个1出现的位置
    //如果全是0,返回数组长度
    public static int find(int[] a,int low,int high) {
        int flag=0;
        while(high-low>1) {                  //当low,high相邻时,结束  可以知道,low永远在high的左边
            int mid=(low+high)/2;
            if(a[mid]==1) {
                high=mid;
            }else {
                low=mid;
            }
        }
        if(a[low]==1) return low;
        if(a[high]==1) return high;      
        return a.length;
    }
    
    public static void main(String[] args) {
        int[] a= {0,1,1,1,1};        //最好多举例,演示几遍就清楚了
        int f=find(a,0,a.length-1);  
        System.out.println(f);
    }
}

 

posted @ 2018-05-05 23:51  嘿boom  阅读(1050)  评论(0编辑  收藏  举报