美文网首页
Oct-23-2018

Oct-23-2018

作者: 雨生_ | 来源:发表于2018-10-23 21:54 被阅读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;
}
Github

相关文章

  • Oct-23-2018

    争取每周做五个LeedCode题,定期更新,难度由简到难 Title: Search Insert Positio...

网友评论

      本文标题:Oct-23-2018

      本文链接:https://www.haomeiwen.com/subject/dndzzftx.html