Leetcode刷题记——34. Search for a Range(查找一个范围)
来源:互联网 发布:淘宝诈骗 济宁 编辑:程序博客网 时间:2024/05/29 02:04
一、题目叙述:
Given a sorted array of integers, 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
Subscribe to see which companies asked this question
二、解题思路:
关键字:二分查找。
1、本题给定一个已经排序好的数组和一个值,要求返回该值在数组中的一个下标范围,使用二分查找,在找不到的情况下,直接返回-1,-1。
2、在找到这个值后,根据返回的位置,分别从返回下标的位置左半边二分查找该值,直到找不到为止,以确定范围最左边的下标;同理去右半边二分查找,以确定范围右边的下标。
三、源码:
import java.util.Arrays;public class Solution{ public int[] searchRange(int[] nums, int target) { int[] result = {-1, -1}; if (search(0, nums.length - 1, nums, target) < 0) return result; else { int left, right; left = right = search(0, nums.length - 1, nums, target); //result[0] = result[1] = mid; while (left >= 0) { result[0] = left; left = search(0, left - 1, nums, target); } while (right >= 0) { result[1] = right; right = search(right + 1, nums.length - 1, nums, target); } } return result; } public int search(int lo, int hi, int[] nums, int target) { while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] < target) lo = mid + 1; else if (nums[mid] > target) hi = mid - 1; else return mid; } return -1; } public static void main(String args[]) { int[] nums = {1,1,1,1,1}; Solution solution = new Solution(); System.out.println(Arrays.toString(solution.searchRange(nums, 1))); }}
0 0
- Leetcode刷题记——34. Search for a Range(查找一个范围)
- LeetCode-----34. Search for a Range(查找范围)
- [LeetCode]—Search for a Range 有序数组查找target的下标范围
- LeetCode OJ 之 Search for a Range (查找一个范围)
- Search for a Range 查找一个数所在的范围
- [leetcode] 【查找】 34. Search for a Range
- Leetcode #34. Search for a Range 范围搜寻 解题报告
- LeetCode 34. Search for a Range(搜索范围)
- [LeetCode] Search for a Range查找区间
- leetcode:Search for a Range 二分查找
- leetcode 二分查找 Search for a Range
- leetcode-二分查找:Search for a range
- leetcode---search-for-a-range---查找
- Search for a Range--查找某个数范围--二分查找
- LeetCode —— Search for a Range
- LeetCode——Search for a Range
- LeetCode——Search for a Range
- leetcode——Search for a Range
- Objective-c常用的函数,常数变量
- Nodejs下MySQL数据库链接释放问题详解
- 05、一步一步学thinkjs之model增删改查
- GOF23的一些总结(六)
- IIS应用发布(三)
- Leetcode刷题记——34. Search for a Range(查找一个范围)
- 为什么很多第三方接口,都改成了基于http,直接传递json数据的方式来代替webservice?
- 在前端中什么是组件化 什么是模块化
- Xcode8.1 cocoa application中关于View Controller下设置项"Is Initial Controller"的问题
- 前端开发的模块化和组件化的定义,以及两者的关系?
- GCD-Barrier
- centos 7 yum源文件配置详解及163 yum源更换
- spring mybatis 设置settings操作
- postgresql的一些使用技巧