且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

搜寻最小大数的算法需要说明

更新时间:2023-02-26 18:13:15

所以代码的作用是使用一种形式的二进制搜索(在这里,

So what the code does is using a form of binary search (How binary search works is explained quite nicely here, https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/. It also uses an example quite similar to your problem.). Where you search for the minimum sum every block needs to contain. In the example case, you need the divide the array in 3 parts

进行二进制搜索时,您需要定义2个边界,可以确定在两个边界之间找到答案.此处,下边界是数组(lower)中的最大值.对于此示例,该值为5(这是将数组分成7个块的情况).

When doing a binary search you need to define 2 boundaries, where you are certain that your answer can be found in between. Here, the lower boundary is the maximum value in the array (lower). For the example, this is 5 (this is if you divide your array in 7 blocks). The upper boundary (upper) is 15, which is the sum of all the elements in the array (this is if you divide the array in 1 block.)

现在是搜索部分:在solution()中,您从边界和中点开始(示例为10). 在calculateBlockCount中,您计算​​(count ++这样),如果总和最大为10(在calculateBlockCount中为中间点/或maxSum),则可以进行多少个块.
对于示例10(在while循环中),这是2个块,现在代码将此(blocks)返回到solution.然后,它检查是小于还是大于K,这是所需的块数.如果它的值小于K,则您的mid点很高,因为要在块中放入许多数组元素.如果它大于K,则说明您的mid点太高,并且您在数组中放置的数组元素太少. 现在在检查之后,将求解空间减半(upper = mid-1). 这种情况在每个循环中都会发生,它使解决方案空间减半,从而使其收敛非常快.

Now comes the search part: In solution() you start with your bounds and mid point (10 for the example). In calculateBlockCount you count (count ++ does that) how many blocks you can make if your sum is a maximum of 10 (your middle point/ or maxSum in calculateBlockCount).
For the example 10 (in the while loop) this is 2 blocks, now the code returns this (blocks) to solution. Then it checks whether is less or more than K, which is the number of blocks you want. If its less than K your mid point is high because you're putting to many array elements in your blocks. If it's more than K, than your mid point is too high and you're putting too little array elements in your array. Now after the checking this, it halves the solution space (upper = mid-1). This happens every loop, it halves the solution space which makes it converge quite quickly.

现在,您在调整mid的同时继续进行操作,直到给出输入K中的数量块为止.

Now you keep going through your while adjusting the mid, till this gives the amount blocks which was in your input K.

所以要逐步进行:

Mid =10 , calculateBlockCount returns 2 blocks
solution. 2 blocks < K so upper -> mid-1 =9, mid -> 7  (lower is 5)
Mid =7 , calculateBlockCount returns 2 blocks  
solution() 2 blocks < K so upper -> mid-1 =6, mid -> 5 (lower is 5, cast to int makes it 5)
Mid =5 , calculateBlockCount returns 4 blocks
solution() 4 blocks < K so lower -> mid+1 =6, mid -> 6  (lower is 6, upper is 6
Mid =6 , calculateBlockCount returns 3 blocks
So the function returns mid =6....

希望这会有所帮助,

GL学习编码:)