LeetCode 374 Guess the size (about dichotomy exists in the problem-solving process problems)

There are already a lot of blog has ideas and methods to solve LeetCode374 made a detailed explanation, I am here only a brief speech, the problem I encountered in doing this topic!
The solution is to use the principle of dichotomy to find given that number, every time cut in half the space search!
In the calculation of an intermediate value, mid have two formulas:

mid = (low + high) / 2;
mid = low + (high - low) / 2;

The difference between these two formulas is: When looking for a small range of time, can be used; but when a wide range of time, low + high, there may appear to overflow, which run error!
Of course, in this case, the program will not necessarily run error (there will time out after submission process, while on their machines are programmed not stop);
beginning just feel Find a dichotomous still not very familiar with, may border cycle is out of the question, but after examination found that this is not the reason;
by Baidu and discussion with the students, they finally know is too big a number, and when the accumulated overflow has occurred, resulting in cache space problems, crashes!
Baidu a moment later, this is generally not overflow error or display an error message, so the situation will be running overtime!
In summary, when after using a binary search, try to use the second formula, to avoid overflow!

Published 33 original articles · won praise 3 · Views 6318

Guess you like

Origin blog.csdn.net/m0_37683327/article/details/103955941