问题

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

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

输入: [1,3,5,6], 5

输出: 2

输入: [1,3,5,6], 2

输出: 1

输入: [1,3,5,6], 7

输出: 4

输入: [1,3,5,6], 0

输出: 0


Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Input: [1,3,5,6], 5

Output: 2

Input: [1,3,5,6], 2

Input: 1

Input: [1,3,5,6], 7

Input: 4

Input: [1,3,5,6], 0

Input: 0


示例

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

public class Program {

    public static void Main(string[] args) {
int[] nums = { 1, 3, 5, 6 }; Console.WriteLine(SearchInsert(nums, 2));
Console.WriteLine(SearchInsert2(nums, 6)); Console.ReadKey();
} private static int SearchInsert(int[] nums, int target) {
for(int i = 0; i < nums.Length; i++) {
if(nums[i] >= target) return i;
}
return nums.Length;
} private static int SearchInsert2(int[] nums, int target) {
int mid = 0, low = 0;
int high = nums.Length - 1; while(low <= high) {
mid = low + (high - low) / 2; if(nums[mid] == target) {
return mid;
} else if(nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
} return low;
} }

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

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

1
3

分析:

显而易见,SearchInsert在最坏的情况下的时间复杂度为:  , SearchInsert2在最坏的情况下的时间复杂度为:  。

最新文章

  1. JS实战 &#183; 表单验证
  2. (原创)JAVA多线程一传统多线程
  3. 【krpano】krpano xml资源解密(破解)软件说明与下载(v1.2)
  4. 最简单的Github入门基础
  5. 关于Entity Framework中的Attached报错的完美解决方案终极版
  6. 第8章 用户模式下的线程同步(2)_临界区(CRITICAL_SECTION)
  7. [转]解决ubuntu下面putty不能连接RS232串口(USB2COM线)
  8. 转:深入理解JavaScript闭包概念
  9. AppleScript
  10. Quartz Cron表达式生成器
  11. Android Java混淆(ProGuard)
  12. js、jquery、css使用过程中学到的一些方法技巧
  13. 给公司部门设计的SOA架构(转)
  14. IIS安装asp组件:JMail 邮件收发组件
  15. C#进阶系列——使用Advanced Installer制作IIS安装包(一:配置IIS和Web.config)
  16. Spring Cloud在国内中小型公司能用起来吗?
  17. python的出生
  18. JavaScript学习之路-为什么要学习JavaScript语法
  19. 《Go语言实战》摘录:7.1 并发模式 - runner
  20. ViewPager一屏显示多个item,及边缘滑动事件优化

热门文章

  1. 项目管理:如何显性管理并提升Story分解能力
  2. X-Tag实战:给博客加一个隐藏侧栏的功能
  3. Vue.js +pdf.js 处理响应pdf文件流数据,前端转图片预览不可下载
  4. 【Redis学习专题】- Redis主从+哨兵集群部署
  5. Netty 学习笔记(1) ------ Hello World
  6. 【原创】xenomai内核解析--同步互斥机制(一)--优先级倒置
  7. 学Python入门应该先学什么?看完本文你就知道了
  8. SQL语法入门
  9. 阿里云OSS服务器的使用
  10. Elasticsearch及相关插件的安装