记录九——搜索插入位置

搜索插入位置

题:给出一个排序好的数组nums和一个目标值target,如果数组中存在该目标值,返回该目标值的索引。若数组中没有该目标值,返回该目标值应该插入位置的索引。
Input: [1,3,5,6], 5
Output: 2


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


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


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


思路:遍历一遍该数组,将目标值与数组中的每一个元素做比较,判断是否存目标值,若存在,返回索引,若不存在,判断是在哪两个索引元素中间,返回索引。
代码:

class Solution {
    public int searchInsert(int[] nums, int target) {
        int index = 0;
        if(nums[0] == target) return index;
        if(nums[nums.length - 1] < target) return nums.length ;
        for(int i = 1; i < nums.length;i++){
            if(nums[i] == target){
                index = i ; 
            }
            if(target > nums[i - 1] && target < nums[i]){
                index = i ;
            }
        }
        return index;
    }
}

还是要多思考,多动手。

猜你喜欢

转载自blog.csdn.net/w1375834506/article/details/88412679