您的位置:首页 > 其它

lintcode之Wood-Cut问题

2016-06-28 11:08 417 查看
1. 问题描述



2. java解法

2.1 SolutionWoodCut.java

import java.lang.*;
/**
* @wood-cut problem
* @author xin_wang
*
*/
public class SolutionWoodCut {

public int woodcut(int[] L,int k){
//find longest wood in L[];
int max=0;
for (int i=0; i<L.length; i++){
max=Math.max(max,L[i]);
}

//binary-search method to get common longest length
int start=1;
int end=max;
while (start+1<end){
int mid=start+(end-start)/2;
if (count(L,mid)==k){
return mid;
}else if (count(L,mid)>k){
start = mid;
}else{
end = mid;
}
}
if (count(L,start)==k){
return start;
}
if (count(L,end)==k){
return end;
}
return 0;
}

//count pieces under common longest length
private int count(int[] L,int Length){
int sum=0;
for (int i=0 ; i<L.length ; i++){
sum+= L[i]/Length;
}
return sum;
}
}

2.2 woodcutTest.java
public class woodcutTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] A = {232,124,456};
int k = 7;
SolutionWoodCut s1 = new SolutionWoodCut();
System.out.println(s1.woodcut(A,k));
}
}
3. 输出结果:114
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息