作者:MJ昊
公众号:程序猿的编程之路
今天是 昊 算法之路的第3天,我很高兴能和大家一起探索编程的乐趣。
为大家讲解LeetCode第2774题,难易程度:简单
题目描述
请你编写代码实现一个数组方法,任何数组都可以调用 upperBound() 方法,并返回给定目标数字的最后一个索引。nums 是一个可能包含重复数字的按升序排序的数组。如果在数组中找不到目标数字,则返回-1。
示例 1:
输入: nums = [3,4,5], target = 5
输出: 2
解释: 目标值的最后一个索引是 2
示例 2:
输入: nums = [1,4,5], target = 2
输出: -1
解释: 因为数组中没有数字 2,所以返回 -1。
示例 3:
输入: nums = [3,4,6,6,6,6,7], target = 6
输出: 5
解释: 目标值的最后一个索引是 5
提示:
1 <= nums.length <= 104
-104 <= nums[i], target <= 104
nums按升序排序。
解题思路
解题方法:循环处理法
/**
* @param {number} target
* @return {number}
*/
Array.prototype.upperBound = function(target) {
if (!Array.isArray(this)) {
throw new TypeError("Not an array");
}
for (let index = this.length - 1; index >= 0; index--) {
const element = this[index];
if (target === element) {
return index
}
}
return -1
};
复杂度分析
- 时间复杂度:
O(n),在最坏情况下需要遍历整个数组。 - 空间复杂度:
O(1),没有使用额外的空间。
解题方法:二分查找法
Array.prototype.upperBound = function(target) {
let left = 0, right = this.length - 1, result = -1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (this[mid] === target) {
result = mid; // 记录最后找到的索引
left = mid + 1; // 继续查找右半边
} else if (this[mid] < target) {
left = mid + 1; // 查找右半边
} else {
right = mid - 1; // 查找左半边
}
}
return result;
};
复杂度分析
- 时间复杂度:
O(log n),因为使用了二分查找。 - 空间复杂度:
O(1),没有使用额外的空间。
总结
通过这道题目,我进一步加深了对数组方法的理解,并实践了不同的解法。作为一名写作小白,我希望通过持续的学习与分享,提升自己的能力。感谢大家的阅读,期待你们的反馈与讨论!如果你有更好的解法或见解,欢迎在评论区与我分享!