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
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
相关文章推荐
- C++二分查找在搜索引擎多文档求交的应用分析
- C语言编程中实现二分查找的简单入门实例
- C#二分查找算法实例分析
- 二分查找算法在C/C++程序中的应用示例
- 在MySQL中实现二分查找的详细教程
- Java实现二分查找算法实例分析
- Python基于二分查找实现求整数平方根的方法
- python二分查找算法的递归实现方法
- Python二分查找详解
- 简介二分查找算法与相关的Python实现示例
- python二分查找算法的递归实现方法
- Python基于二分查找实现求整数平方根的方法
- 漫谈递归:二分查找算法的递归实现
- 二分查找
- [LeetCode] Find Minimum in Rotated Sorted Array
- 折半查找法
- "二分查找(Binary Search)"与"斐波那契查找(Fibonacci Search)"
- 二分查找
- C#版二分查找(代碼)
- 4495: Least Prime factor 找到最小质因子P的第N小正整数