LeetCode刷题--35. 搜索插入位置(简单)

题目描述

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

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

示例 1:

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

示例 2:

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

示例 3:

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

示例 4:

输入: [1,3,5,6], 0
输出: 0

思路:二分法

  • 如果该题目暴力解决的话需要 O(n)的时间复杂度,但是如果二分的话则可以降低到 O(logn)的时间复杂度
  • 先设定左侧下标 left 和右侧下标 right,再计算中间下标 mid
  • 每次根据 nums[mid] 和 target 之间的大小进行判断,相等则直接返回下标,nums[mid] < target left右移,nums[mid] > target 则 right 左移
  • 查找结束如果没有相等值则返回 left,该值为插入位置
  • 二分查找的思路不难理解,但是边界条件容易出错,比如 循环结束条件中 left 和 right 的关系,更新 left 和 right 位置时要不要加 1 减 1。

模板

模板记住就好,免除边界条件出错。

class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1; // 注意
        while(left <= right) { // 注意
            int mid = (left + right) / 2; // 注意
            if(nums[mid] == target) { // 注意
                // 相关逻辑
            } else if(nums[mid] < target) {
                left = mid + 1; // 注意
            } else {
                right = mid - 1; // 注意
            }
        }
        // 相关返回值
        return 0;
    }
}

代码实现

class Solution {
    public int searchInsert(int[] nums, int target) {
        //定义左侧下标left和右侧下标right
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            //当nums[mid]和目标元素相等时,直接返回
            if (nums[mid] == target) {
                return mid;
                //当nums[mid]小于目标元素时,left右移  [mid+1,right]为下一个区间
            } else if (nums[mid] < target) {
                left = mid + 1;
                //反之,当nums[mid]大于目标元素时,right左移  [left,mid-1]为下一个区间
            } else {
                right = mid - 1;
            }
        }
        //查找结束如果没有相等值则返回 left,该值为插入位置
        return left;
    }
}

原文地址:https://www.cnblogs.com/xiaozhongfeixiang/p/12439277.html

时间: 2024-08-04 12:30:19

LeetCode刷题--35. 搜索插入位置(简单)的相关文章

leetCode 第35题,搜索插入位置

题目概述 题目:力扣:35.搜索插入位置 难易:简单 内容: 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引.如果目标值不存在于数组中,返回它将会被按顺序插入的位置. 你可以假设数组中无重复元素. 示例 1: 输入: [1,3,5,6], 5 输出: 2 示例 2: 输入: [1,3,5,6], 2 输出: 1 示例 3: 输入: [1,3,5,6], 7 输出: 4 示例 4: 输入: [1,3,5,6], 0 输出: 0 来源:力扣(LeetCode) 链接:https://

leetcode 刷题之路 70 earch Insert Position 二分查找插入位置

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2

[leetcode] 35. 搜索插入位置(Java)(二分)

35. 搜索插入位置 二分,太简单,没啥好说的 class Solution { public int searchInsert(int[] nums, int target) { if (nums.length == 0) return 0; int i = 0, j = nums.length; int mid = (i + j) / 2; while (i < j) { if (nums[mid] == target) { return mid; } else if (nums[mid]

【leetcode刷题笔记】Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given:S: "b

【leetcode刷题笔记】3Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solut

【leetcode刷题笔记】Restore IP Addresses

Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example:Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) 题解:深度优先搜索.用resul

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Sort List

Sort a linked list in O(n log n) time using constant space complexity. 题解:实现一个链表的归并排序即可.主要分为三部分: 1.找到中点并返回的函数findMiddle; 2.归并函数merge; 3.排序函数sortList. 数组的findMiddle函数非常容易实现,链表就有一点tricky了.首先设置两个指针,一个slow初始化为head,一个fast初始化为head.next,然后slow一次走一步,fast一次走两

【leetcode刷题笔记】Maximal Rectangle

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. 题解,很巧妙的一道题,对于一个0-1矩阵,它的每一行及以上都可以看作一个直方图(如下图所示),利用Largest Rectangle in Histogram的方法,可以在O(n)的时间搜索出这一行及以上的直方图中面积最大的矩形,对矩阵的每一行依次做这个操作,就可