C#LeetCode刷题之#35-搜索插入位置(Search Insert Position)
问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 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在最坏的情况下的时间复杂度为: 。
最新文章
- JS实战 &#183; 表单验证
- (原创)JAVA多线程一传统多线程
- 【krpano】krpano xml资源解密(破解)软件说明与下载(v1.2)
- 最简单的Github入门基础
- 关于Entity Framework中的Attached报错的完美解决方案终极版
- 第8章 用户模式下的线程同步(2)_临界区(CRITICAL_SECTION)
- [转]解决ubuntu下面putty不能连接RS232串口(USB2COM线)
- 转:深入理解JavaScript闭包概念
- AppleScript
- Quartz Cron表达式生成器
- Android Java混淆(ProGuard)
- js、jquery、css使用过程中学到的一些方法技巧
- 给公司部门设计的SOA架构(转)
- IIS安装asp组件:JMail 邮件收发组件
- C#进阶系列——使用Advanced Installer制作IIS安装包(一:配置IIS和Web.config)
- Spring Cloud在国内中小型公司能用起来吗?
- python的出生
- JavaScript学习之路-为什么要学习JavaScript语法
- 《Go语言实战》摘录:7.1 并发模式 - runner
- ViewPager一屏显示多个item,及边缘滑动事件优化