算法题 N根绳子截M段问题

2019春招 字节跳动笔试题 第4题

题目

给n根绳子,分别记其长度为L1-Ln。现要从这些绳子中截出等长的m段,求这些绳子长度的最大值。
比如3根绳子长度 1,3,4,截成3段,则最大值为2(1不截,3截一段,4截2段)

看了下网上大佬的思路,感觉没什么问题,写下来记录一下。(可能有误,毕竟没提交试试能否AC)

https://blog.csdn.net/coc0nut/article/details/88617630

import java.util.Scanner;

public class Test{
	public static void main(String[] args) {
		TouTiao_4();
	}
	public static void TouTiao_4(){
		// 处理输入
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		double[] len = new double[n];
		for(int i=0; i<n; i++)
			len[i] = sc.nextDouble();
		// 初始化
		double ans = 0;
		double[] temp = new double[n];
		int[] num = new int[n];
		for(int i=0; i<n; i++){
			temp[i] = len[i];
			num[i] = 1;
		}
		// 从M=1开始,从简到繁,推出M=m的解
		for(int i=0; i<m; i++){
			double[] res = findMaxLen(temp);
			int index = (int)res[0];
			ans = res[1];
			num[(int) index] ++;
			temp[index] = len[index] / num[index];
		}
		System.out.println(ans);
	}
	
	/*
	 * 传入数组,返回最大值及其下标
	 */
	public static double[] findMaxLen(double[] l){
		int len = l.length;
		double max = 0;
		int index = 0;
		for(int i=0; i<len; i++){
			if(l[i] > max){
				index = i;
				max = l[i];
			}
		}
		double[] res = new double[2];
		res[0] = index;
		res[1] = max;
		return res;
	}
}

为了看得更清晰,推算过程:

拿 1,2,5 分成4段举例:

m=1
numtemp
11
1

2

15
m=2
numtemp
11
1

2

2

2.5

m=3
numtemp
11
1

2

35/3
m=4
numtemp
11
2

1

35/3
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值