【LeetCode】Search for a Range
2016-03-06 21:26
483 查看
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].
题目大意:在一个已经排好序的整型数组中找出某个数的范围(最大下标和最小下标),如果这个数不存在,返回[-1,-1]。
思路一:从左向右遍历数组,直至找到该数的范围或不存在,复杂度为o(n),很明显还有更好的方法,可以提高效率。
思路二:使用二分查找的思想
代码如下:
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].
题目大意:在一个已经排好序的整型数组中找出某个数的范围(最大下标和最小下标),如果这个数不存在,返回[-1,-1]。
思路一:从左向右遍历数组,直至找到该数的范围或不存在,复杂度为o(n),很明显还有更好的方法,可以提高效率。
思路二:使用二分查找的思想
代码如下:
public int[] searchRange(int[] nums, int target) { int[] ans = new int[2];//返回数组指针,动态分配内存 if(nums == null || nums.length == 0) { ans[0] = -1; ans[1] = -1; return ans; } int left = 0; int right = nums.length-1; int mid = 0; int flag = 0; while(left <= right) { mid = (left + right) / 2; if(nums[mid] == target) { flag = 1; break; } else if(nums[mid] < target){ left = mid + 1; } else { right = mid - 1; } } if(flag == 1) {//找到了 int index1 = mid; int index2 = mid; while(index1-1 >= 0 && nums[index1-1] == target) {//index1-1 >= 0防止数组越界 index1--; } while(index2+1 < nums.length && nums[index2+1] == target) { index2++; } ans[0] = index1; ans[1] = index2; } else { ans[0] = -1; ans[1] = -1; } return ans; }
相关文章推荐
- 计数排序
- js日期插件
- Android学习笔记之Intent(2)
- 迷茫的软件工程
- js日期插件
- js日期插件
- hadoop 生态圈
- 我的AngularJs第一课
- Apache和Tomcat服务器间的区别、联系、整合详细介绍
- Ubuntu root 密码忘记-恢复
- 关于软件工程我的一些想法
- 探究java多线程中正确的单例模式 volatile关键字
- Js中的with
- iOS. UIButton 常用方法
- ubuntu 14.04 登录 界面 root
- MOOC《Linux内核分析》第二课
- windows程序设计学习笔记-Unicode,绘图基础
- 软件工程随笔
- apache 开启Gzip网页压缩
- apache 开启Gzip网页压缩