zoukankan      html  css  js  c++  java
  • [leetcode]35. 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.

    Example 1:

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

    Example 2:

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

    Example 3:

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

    Example 4:

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

    题意:

    给定有序数组和一个target,寻找合适的插入位置。

    Solution1: Binary Search

    数组元素有偶数个时, 中点若取偏左端的那个

    1   2   3   4

            ^mid

    那么,更新left时,从mid + 1 开始

    code:

     1 /*
     2 Time: O(log(n))
     3 Space: O(1)
     4 */
     5 class Solution {
     6    public int searchInsert(int[] nums, int target) {
     7         //corner case
     8         if (nums == null || nums.length == 0) {
     9             return 0;
    10         }
    11         if (target < nums[0]) {   //[1,3,5,6], 0
    12             return 0;
    13         } else if (target > nums[nums.length - 1]) {  // [1,3,5,6], 7
    14             return nums.length;
    15         }
    16         // binary search
    17         int left = 0, right = nums.length - 1;
    18         while (left < right) {
    19             int mid = left + (right - left) / 2;
    20             if (nums[mid] == target) {
    21                 return mid;
    22             } else if (nums[mid] > target) {
    23                 right = mid;
    24             } else {
    25                 left = mid + 1;
    26             }
    27         }
    28         return left;
    29     }
    30 }
  • 相关阅读:
    Linux下安装JDK
    Flink源码阅读(五)——Flink中任务相关的核心类简析
    使用CloudFlare Worker 来免费部署 JSProxy 服务
    Nginx:进程调度
    Javassist基本用法汇总
    IO
    IO
    springcloud3(五) spring cloud gateway动态路由的四类实现方式
    架构设计(二) 互联网网关平台对比
    Python 的协程
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10693756.html
Copyright © 2011-2022 走看看