如何做网站哪个站推广,描述对于营销型网站建设很重要飘红效果更佳,天津装修公司做网站,临沧市住房和城乡建设局门户网站给定一个排序数组和一个目标值#xff0c;在数组中找到目标值#xff0c;并返回其索引。如果目标值不存在于数组中#xff0c;返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例 1: 输入: nums [1,3,5,6], target 5
输出: 2示例 2: 输入: …给定一个排序数组和一个目标值在数组中找到目标值并返回其索引。如果目标值不存在于数组中返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例 1: 输入: nums [1,3,5,6], target 5
输出: 2示例 2: 输入: nums [1,3,5,6], target 2
输出: 1示例 3: 输入: nums [1,3,5,6], target 7
输出: 4提示:
1 nums.length 10^4-10^4 nums[i] 10^4nums 为 无重复元素 的 升序 排列数组-10^4 target 10^4
我的解答
class Solution {public int searchInsert(int[] nums, int target) {int l 0, r nums.length - 1;int p 0;while(l r){p (l r) / 2;if(nums[p] target) return p;else if(nums[p] target) l p 1;else r p - 1;}return l;}
}