问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4970 访问。

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

你的算法时间复杂度必须是 O(log n) 级别。

如果数组中不存在目标值,返回 [-1, -1]

输入: nums = [5,7,7,8,8,10], target = 8

输出: [3,4]

输入: nums = [5,7,7,8,8,10], target = 6

输出: [-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].

Input: nums = [5,7,7,8,8,10], target = 8

Output: [3,4]

Input: nums = [5,7,7,8,8,10], target = 6

Output: [-1,-1]


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4970 访问。

public class Program {

    public static void Main(string[] args) {
var nums = new int[] { 2, 2 }; var res = SearchRange(nums, 2);
ShowArray(res); nums = new int[] { 5, 7, 7, 8, 8, 10 }; res = SearchRange2(nums, 8);
ShowArray(res); Console.ReadKey();
} private static void ShowArray(int[] array) {
foreach(var num in array) {
Console.Write($"{num} ");
}
Console.WriteLine();
} public static int[] SearchRange(int[] nums, int target) {
//暴力线性
var res = new int[] { -1, -1 };
for(int i = 0, j = nums.Length - 1;
i <= j && (res[0] == -1 || res[1] == -1);) {
if(nums[i] == target) res[0] = i; else i++;
if(nums[j] == target) res[1] = j; else j--;
}
return res;
} public static int[] SearchRange2(int[] nums, int target) {
//二分法
var low = 0;
var high = nums.Length - 1;
var mid = 0;
var res = new List<int>();
while(low <= high) {
mid = low + (high - low) / 2;
if(nums[mid] == target) {
var index = mid;
while(index < high) {
if(nums[++index] != target) {
index--;
break;
}
}
res.Add(index);
index = mid;
while(index > 0) {
if(nums[--index] != target) {
index++;
break;
}
}
res.Insert(0, index);
return res.ToArray();
} else if(nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
res.Add(-1);
res.Add(-1);
return res.ToArray();
} }

以上给出2种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4970 访问。

0 1
3 4

分析:

显而易见,SearchRange 的时间复杂度为:  ,SearchRange2 的时间复杂度为: 

最新文章

  1. react native 刷新机制----通知
  2. Spring松耦合实例
  3. ProGuard代码混淆技术详解
  4. codeforces B.Maximum Absurdity 解题报告
  5. kinect for windows sdk
  6. 【转】启动 Eclipse 弹出“Failed to load the JNI shared library jvm.dll”错误的解决方法! .
  7. Park Visit
  8. HTML5 CSS3 诱人的实例 :模仿优酷视频截图功能
  9. 将 Java Spring Framework 应用程序迁移到 Windows Azure
  10. 数字三角形-poj
  11. Apache下载、安装及配置(Windows版)
  12. 鼠标拖动DOM
  13. 从hadoop一路配置到spark
  14. Python-常见面试题-持续更新
  15. HDU 5984 数学期望
  16. java中经常使用的快捷键
  17. [Firebase] 3. Firebase Simple Login Form
  18. java中的super限定
  19. Pandas中数据的处理
  20. python中format()方法格式化字符串

热门文章

  1. Linux下一只五颜六色的「猫」
  2. toad for oracle 小技巧
  3. xenomai内核解析之信号signal(一)---Linux信号机制
  4. less : 解决升级后报错的问题
  5. C++语法小记---面向对象模型(实例的内存分布)
  6. C踩坑纪实——(一)
  7. HBase面试考点
  8. python socket函数详解
  9. Oracle 忘记密码 如何修改
  10. Python while 中简单的语句组