Problem: 793. 阶乘函数后 K 个零
文章目录
- 题目描述
- 思路即解法
- 复杂度
- Code
题目描述
思路即解法
1.根据题意可知即是要求取满足条件的n最小是多少,最大是多少,最大值和最小值一减,就可以算出来有多少个n满足条件了。
2.由于题目中的阶乘存在单调性则可以使用二分查找来解决,具体的利用一个辅助函数求取出每一个n的阶乘后的0的个数,再利用二分查找找出满足条件的n的左边界和有边界
复杂度
时间复杂度:
O ( 1 ) O(1) O(1);若不限制数据范围则为 O ( l o g N × l o g N ) O(logN \times logN) O(logN×logN)
空间复杂度:
O ( 1 ) O(1) O(1)
Code
class Solution {/*** Preimage Size of Factorial Zeroes Function** @param k Given number* @return int*/public int preimageSizeFZF(int k) {// The difference between the left and right boundaries + 1 is the answerreturn (int) (right_bound(k) - left_bound(k) + 1);}/*** Search for the left boundary of trailingZeroes(n) == K** @param target The target* @return long*/private long left_bound(int target) {long low = 0;long high = Long.MAX_VALUE;while (low < high) {long mid = low + (high - low) / 2;if (trailingZeroes(mid) < target) {low = mid + 1;} else if (trailingZeroes(mid) > target) {high = mid;} else {high = mid;}}return low;}/*** Search for the right boundary of trailingZeroes(n) == K** @param target The target* @return long*/private long right_bound(int target) {long low = 0;long high = Long.MAX_VALUE;while (low < high) {long mid = low + (high - low) / 2;if (trailingZeroes(mid) < target) {low = mid + 1;} else if (trailingZeroes(mid) > target) {high = mid;} else {low = mid + 1;}}return low - 1;}/*** Find the number of zeros after the factorial of a given number** @param n Given number* @return long*/private long trailingZeroes(long n) {long res = 0;for (long d = n; d / 5 > 0; d = d / 5) {res += d / 5;}return res;}
}