First, the array --- Search Insert location

Given a sorted array and a target, find the object in the array, and returns its index. If the target is not present in the array, it will be returned in sequence inserted position.

You may assume that no duplicate elements in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2
Example 2:

Input: [1,3,5,6], 2
Output: 1
Example 3:

Input: [1,3,5,6], 7
Output: 4
Example 4:

Input: [1,3,5,6], 0
Output: 0

 1 class Solution {
 2 public:
 3     int searchInsert(vector<int>& nums, int target) {
 4         int len = nums.size();
 5         if(len == 0) return 0;
 6         for(int i=0;i<nums.size();i++){
 7             if(nums[i] >= target){
 8                 return i;
 9             }
10         }
11         return len;
12     }
13 };

 

Guess you like

Origin www.cnblogs.com/pacino12134/p/10988825.html