LintCode Wood Cut java solution

来源:互联网 发布:华为运营商网络业务 编辑:程序博客网 时间:2024/05/17 01:44

题目要求:
Given n pieces of wood with length L[i] (integer array). Cut them into small pieces to guarantee you could have equal or more than k pieces with the same length. What is the longest length you can get from the n pieces of wood? Given L & k, return the maximum length of the small pieces.

Notice

You couldn’t cut wood into float length.

If you couldn’t get >= k pieces, return 0
Example
For L=[232, 124, 456], k=7, return 114.
解题思路:题目中的最大的长度是数组中的最长数字, 最短是1.

public class Solution {    public int woodCut(int[] L, int k) {        if (L == null || L.length == 0) {            return 0;        }        int start = 1;        int end = findMax(L);        while (start + 1 < end) {            int mid = start + (end - start) / 2;            if (countWood(L, mid) == k) {                start = mid;            } else if (countWood(L, mid) < k) {                end = mid;            } else {                start = mid;            }        }        if (countWood(L, end) <= k) {            return end;        }        if (countWood(L, start) <= k) {            return start;        }        return 0;    }    private int findMax(int[] nums) {        int max = nums[0];        for (int i = 0; i < nums.length; i++) {            max = (max < nums[i]) ? nums[i] : max;        }        return max;    }    private int countWood(int[] nums, int len) {        int sum = 0;        for (int i = 0; i < nums.length; i++) {            sum += nums[i] / len;        }        return sum;    }}
0 0
原创粉丝点击