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
题意不说了,直接上代码。
代码如下:
/* * 在一个有序的数组中找到插入位置,遍历即可 * */ public class Solution { public int searchInsert(int[] nums, int target) { if(nums==null || nums.length<=0) return 0; int index=-1; for(int i=0;i<nums.length;i++) { if(target==nums[i]) return i; else if(target<nums[i]) { index=i; break; } } if(index==-1) index=nums.length; return index; } }下面是C++做法,很简单
代码如下:
#include <iostream> #include <vector> using namespace std; class Solution { public: int searchInsert(vector<int>& nums, int target) { for (int i = 0; i < nums.size(); i++) { if (nums[i] >= target) return i; } return nums.size(); } };