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 }
  • 相关阅读:
    性能分析之路-------各指标代表意思以及分析
    selenium python 定位一组对象
    python 操作word文档
    nmon的安装以及使用
    nginx的监控配置
    selenium 一个简单的流程
    Fiddler手机抓包设置
    urllib、urllib2、urllib3区别和使用
    mysql数据库改名的方法
    Python之pymysql
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10693756.html
Copyright © 2011-2022 走看看