注意一下binarySearch的返回值,当找不到的时候,会返回(-插入值-1),插入值是这个元素应该插入的位置,我们要找的是,比这个数小一点的数,所以我们需要减去-index-2下标的数。
class Solution {
public int findMinFibonacciNumbers(int k) {
int[] temp = new int[45];
temp[0] = 1;
temp[1] = 1;
int i;
for (i = 2; temp[i - 1] <= k; i++) {
temp[i] = temp[i - 1] + temp[i - 2];
}
// 此时temp[i - 2] <= k && temp[i - 1] > k
k -= temp[i - 2];
int ans = 1;
int end = i - 2;
while (k != 0) {
int index = Arrays.binarySearch(temp, 0, end, k);
if (index >= 0) {
ans++;
break;
}
index = -index - 2;
k -= temp[index];
ans++;
end = index;
}
return ans;
}
}

该博客探讨了一种寻找斐波那契数列中最小数的方法,利用二分查找优化了查找过程。在找到目标数后,通过更新索引并减去相应值来确定所需斐波那契数的个数。这种方法提高了效率,减少了计算次数。
450

被折叠的 条评论
为什么被折叠?



