LeeCode from 0 ——35. Search Insert Position

35. 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.

解题思路:

1)数组为空或者target小于数组第一个元素返回0;

2)target大于数组最后一个元素返回数组长度;

3)若target等于数组中间的某个元素,返回该元素的位置,target若大于数组中一个元素,并且小于其后一个元素,则返回后一个元素的位置。

代码如下:

class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
                          int n=nums.size();
                          if(n==0 || target<nums[0])
                                      return 0;
                          else if(target>nums[n-1])
                                     return n;
                          else{
                                   for(int i=0;i<n;i++){
                                                 if(target==nums[i])
                                                               return i;
                                                else if(target>nums[i] && target<nums[i+1])
                                                               return i+1;
                                      }

                                   }
                             }
                      };

猜你喜欢

转载自www.cnblogs.com/ssml/p/9179898.html