35.搜索插入位置

  • Post author:
  • Post category:其他


1.题目描述

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

请必须使用时间复杂度为 O(log n) 的算法。

2.示例


示例 1:

输入: nums = [1,3,5,6], target = 5
输出: 2


示例 2:

输入: nums = [1,3,5,6], target = 2
输出: 1


示例 3:

输入: nums = [1,3,5,6], target = 7
输出: 4

3.代码实现及思路

package com.yt.leetcode;

/**
 * @auther yt
 * @address https://www.cnblogs.com/y-tao/
 */
public class Test35 {
    public static void main(String[] args) {
        int[] nums = {};
        Solution35 solution35 = new Solution35();
        int searchInsert = solution35.searchInsert(nums, 7);
        System.out.println(searchInsert);

    }
}

//解题思路:
//1.因为传入的数组是有序的,所以如果判断的数字比目标数字大,那么就将目标数字插入到判断数字的前一个位置
//2.如果遍历完毕之后还没有找到插入位置,则插入位置在数组的最后
class Solution35 {
    public int searchInsert(int[] nums,int target) {
        int index = 0;
        int result = 0;
        while (index < nums.length){
            if (nums[index] < target){
                index++;
            } else {
                result = index;
                break;
            }
        }
        if (index == nums.length) {
            result = index;
        }
        return result;
    }
}

4.来源

力扣(LeetCode)

链接:

力扣



版权声明:本文为m0_57385165原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。