zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】Search 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 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0

    解题思路:

    典型的二分查找应用,注意数组下标为0~n-1,但是可能数字需要插在数组最后第n的位置上。

    由于需要找到一个大于等于target数所在的位置,进行插入;所以当nums[mid] > target时,r应该等于mid;因此采用 mid=(l+r)/2,l=mid+1的组合;

    对于二分查找有兴趣的同学,可以看另一道Leetcode题目Search for a Range,对二分查找的应用更加全面,在里面,我也写了一些自己学习二分查找总结的心得;

    代码:

     1 class Solution {
     2 public:
     3     int searchInsert(vector<int>& nums, int target) {
     4         int l = 0;
     5         int r = nums.size();
     6         while (l < r) {
     7             int mid = (l + r) / 2;
     8             if (nums[mid] > target)
     9                 r = mid;
    10             else if (nums[mid] == target) 
    11                 return mid;
    12             else
    13                 l = mid + 1;
    14         }
    15         return r;
    16     }
    17 };
  • 相关阅读:
    单例对象
    G1回收算法
    Java锁
    VUE开发
    Java线程池
    Java线程状态
    什么是进程,什么是线程
    maven 常用命令
    linux启动脚本,暂停脚本
    delphi---控件使用
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4395539.html
Copyright © 2011-2022 走看看