Oct-23-2018
2018-10-23 本文已影响5人
雨生_
争取每周做五个LeedCode题,定期更新,难度由简到难
Title: Search Insert Position
Description:
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
Example:
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 7
Output: 4
Difficulty:
Easy
Implement Programming Language:
C#
Answer:
直接上代码了,粗鲁直接的可以从头遍历,也可以折半查找,不多解释了。
public static int SearchInsert(int[] nums, int target)
{
if (nums.Count() == 0 || nums[0] > target)
return 0;
if (nums.Last() < target)
return nums.Count();
int middle = nums.Count() / 2;
while (nums[middle] >= target)
{
middle /= 2;
}
while (nums[++middle] >= target)
return middle;
return 0;
}