内容简介:Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.Your algorithm's runtime complexity must be in the order of O(log n).If the target is not found in the array, return [-1, -1].
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
难度:medium
题目:
给定一升序整数数组,找出给定整数的起止边界。算法时间复杂度要为O(log n)
思路:二叉搜索
Runtime: 4 ms, faster than 65.40% of Java online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 30.5 MB, less than 28.29% of Java online submissions for Find First and Last Position of Element in Sorted Array.
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
result[0] = binarySearch(nums, false, target);
result[1] = binarySearch(nums, true, target);
return result;
}
// false -> left, true -> right
private int binarySearch(int[] nums, boolean direction, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
if (direction && mid < nums.length - 1 && nums[mid + 1] == target) {
left = mid + 1;
} else if (!direction && mid > 0 && nums[mid - 1] == target) {
right = mid - 1;
} else {
return mid;
}
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
大数据供应链
娜达·R·桑德斯 (Nada R. Sanders) / 丁晓松 / 中国人民大学出版社 / 2015-7-1 / CNY 55.00
第一本大数据供应链落地之道的权威著作,全球顶级供应链管理专家娜达·桑德斯博士聚焦传统供应链模式向大数据转型,助力工业4.0时代智能供应链构建。 在靠大数据驱动供应链处于领先地位的企业中,45% 是零售商,如沃尔玛、亚马逊,而22%是快消企业,如戴尔电脑。他们都前所未有地掌控了自己的供应链。在库存管理、订单履行率、原材料和产品交付上具有更为广阔的视野。利用具有预见性的大数据分析结果,可以使供需......一起来看看 《大数据供应链》 这本书的介绍吧!
html转js在线工具
html转js在线工具
UNIX 时间戳转换
UNIX 时间戳转换