LintCode 183 木材加工

本人电子系,只为一学生。心喜计算机,小编以怡情。

第一次:用遍历的方式,然后超时,死在了[2147483644,2147483645,2147483646,2147483647], 4上

public int woodCut(int[] L, int k) {
        // write your code here
        ArrayList a=new ArrayList<>();
        int max=0;
        int ret=0;
        for(int i=0;ilength;i++)
        {
            if(maxmax=L[i];
        }
        for(int i=1;i<max;i++)
        {
            int count=0;
            for(int j=0;jlength;j++)
            {
                count+=L[j]/i;
            }
            if(count>k)
            {
                ret=i;
                count=0;
            }
            if(count==k)
            {
                ret=i;
                a.add(ret);
            }
        }
        max=0;
        for(int m:a)
        {
            max=max>m?max:m;
        }
            return max;
    }

第二次尝试,是看网上的二分查找方法nlog(n)的查找速度。

 public int woodCut(int[] L, int k) {
        // write your code here

        if(L.length==0) return 0;

        int max=0;//寻找最大值
        for(int i=0;iif(maxlong low=1;//2147483644好烦,一气之下全改long
        long high=max-1;

        while(low<=high)//二分查找逐渐逼近,
        //但是证明应该有数学证明最后收敛的就是想要的。
        //我拿232,124,456,结果为114,结果发现最后low=115,mid=115,high=116    
        //再循环后high=mid-1=114,退出while,得到答案我表示很迷
        //个人猜想是不断逼近使mid恰好为答案+1的位置(如115)
        //然后high=mid-1=114<115得到答案
        //所以求数学帝科普
        {
            long mid=(high+low)/2;
            mid=(int )mid;
            int count=0;
            for(int i=0;icount+=L[i]/mid;

            if(count>=k)//注意这里一定要是>=,
            //否则第一个测试结果是91,即最小的满足值。因此这个条件是能满足k后继续查找,
            //直到收敛到最大的满足值。
                low= (mid+1);
            if(count1);

        }
        return (int)high;

    }

你可能感兴趣的:(LintCode)