LeetCode35. 搜索插入位置
- 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
- 你可以假设数组中无重复元素。
题目比较简单,仅贴代码记录下
只是要注意些特殊情况,不要想着些花里胡哨的优化。以我目前的阶段,安心刷题就好了
class Solution {
public int searchInsert(int[] nums, int target) {
//如果数组长度为0
if (nums.length==0) return 0;
//如果超过数组范围
if (nums[0]>target) return 0;
if (nums[nums.length-1]<target) return nums.length;
//遍历数组
for (int i = 0; i<nums.length;i++){
//如果等于数组某个数
if (target == nums[i]) return i;
//如果不等于数组 某个数,在两个数之间 注意别越界,但是我不需要判断越界,因为当到了最后一个的时候,必然已经返回i了
if (target>nums[i] && target<nums[i+1]) return i+1;
}
return 0;
}
}