35. Search Insert Position(LeetCode)

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

 1 class Solution {
 2 public:
 3     int searchInsert(vector<int>& nums, int target) {
 4             int  local = -1;
 5         vector<int>::iterator ite;
 6         ite=find(nums.begin(), nums.end(), target);
 7         if (ite == nums.end())
 8         {
 9             nums.push_back(target);
10             sort(nums.begin(), nums.end());
11             for (int i = 0; i < nums.size(); i++)
12             {
13                 if (nums[i] == target)
14                     local = i;
15             }
16         }
17         else
18         {
19             for (int i = 0; i < nums.size(); i++)
20             {
21                 if (nums[i] == target)
22                     local = i;
23             }
24         }
25         return local;
26     }
27 };

别人的代码,很聪明

 1 class Solution {
 2 public:
 3     int searchInsert(vector<int>& nums, int target) {
 4          for (int i = 0; i < nums.size(); i++) {
 5             if (target <= nums[i])
 6                 return i;
 7         }
 8         return nums.size();
 9     }
10 };
原文地址:https://www.cnblogs.com/wujufengyun/p/6894562.html