LeetCode编程练习 - Search Insert Position学习心得

题目:

      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.

     Here are few examples.
     [1,3,5,6],5 → 2
     [1,3,5,6],2 → 1
     [1,3,5,6],7 → 4
     [1,3,5,6], 0 → 0

     给定一个排序数组和一个目标值,如果找到目标,返回索引,如果没有则返回按顺序插入目标的索引。假定数组中没有重复项。


思路:

  采用二分查找方法,每次取中间 ,如果与目标相等就返回,否则根据大小关系切去一半。判断while循环中变量i是否<=变量j,若满足条件进入循环,定义一个中间变量n,然后判断这个中间变量所指的数是否与目标值相同,若想同返回中间变量,若大于目标值则将中间变量-1赋值给长度变量j,若小于目标值则对长度变量i+1。

LeetCode编程练习 - Search Insert Position学习心得  

    显示结果:

LeetCode编程练习 - Search Insert Position学习心得