Leetcode 35题 搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

示例 1: 输入: [1,3,5,6], 5  输出: 2  示例 2: 输入: [1,3,5,6], 7  输出: 4

思路1:给定的数组是有序的,先判断目标是是否比数组的第一个元素小(返回下标0)或比最后一个元素大(返回数组长度),然后通过for循环遍历整个数组,判断数组是否存在该元素找到与目标值相等的元素,存在则返回该元素的下标,不存在则插入第一个比目标值大的元素位置。

class Solution {
    public int searchInsert(int[] nums, int target) {
        //所给数组已经排过序
        //Arrays.sort(nums);
        int index=0;
        //判断是否有该元素
        if(target<nums[0])
        {
            return 0;
        }else if(target>nums[nums.length-1])
        {
            return nums.length;
        }else
        {
            for(int i=0;i<nums.length;i++)
            {
                if(nums[i]==target)
                {
                    index = i;
                }else if(target>nums[i]&&target<nums[i+1])
                {
                    index = i+1;
                }
            }
        }
        return index;
    }
}

思路2:因为数组为有序数组,通过for循环遍历数组,如果循环到比target数据大(或相等)的元素,即返回第一个比他大的元素下标;如果没有,则返回数组长度。

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

猜你喜欢

转载自blog.csdn.net/qq_41837911/article/details/83142212