35. Search for Insertion Location
Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, return the position where it will be inserted in order.
You can assume that there are 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
Ideas
This question is relatively simple, and the areas that need to be considered are also very clear. Draw a mind map:
Code
class Solution {
public int searchInsert(int[] nums, int target) {
//排除特殊情况
if(nums.length == 0){
return 0;
}
//遇到相等直接直接返回
for(int i=0 ;i<nums.length; i++){
if(nums[i] == target){
return i;
}
}
int tag = 0;
for(int j = 0; j+1<=nums.length; j++){
//两种特殊情况
if(target < nums[0]){
return 0;
}
if(target > nums[nums.length-1]){
return nums.length;
}
//选择插入位置
if(nums[j] < target && nums[j+1] > target){
tag = j+1;
}
}
return tag;
}
}