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.

    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


    题目标签:Array

      这道题目给了我们一个有序序列,让我们找到target的位置,如果没有target,找到有序嵌入target的位置。利用二分法,来找target,如果没有target,那么最后返回left,就是我们需要嵌入的位置。

      我们来根据code 看原题的例子,当mid < target的话,left 等于 mid + 1; while 条件是包括 left = right。

      [1,3,5,6], 2 -> mid = 3,3 大于2的, 那么范围缩小到 1这个数字, left 和 right 都指向1。1是大于2的,那么left = mid + 1, left 就指向了3, 并且while loop 结束了。 3这个位置就是需要嵌入的地方。

      [1,3,5,6], 7 -> mid = 3, 3 小于 7 的, 那么范围缩小到 left 指向5, right 指向6。 mid = 5, 依然小于7, 那么 left = mid + 1,  left 指向6, right 也指向6。mid = 6, 再一次小于7, left = mid + 1, 就超出了范围,但是这个时候left 指向的是6 后面一位,就是嵌入的位置。

      [1,3,5,6], 0 -> mid = 3 大于0, right = mid - 1; left 指向1, right 指向1。mid = 1, 依然大于0, right = mid - 1;这时候right 已经等于 -1 了。超出了范围,但是left 依然是 0, 而这个 index = 0 的位置就是需要嵌入的位置。

      根据这三个例子的特性,要嵌入的位置,在array 左边是不能超出的,右边是可以超出的。所以我们只要最后return left 就可以了。因为left 只会超过右边。

    Java Solution:

    Runtime beats 70.88% 

    完成日期:03/28/2017

    关键词:Array

    关键点:二分法

     1 public class Solution 
     2 {
     3     public int searchInsert(int[] nums, int target) 
     4     {
     5         int left = 0;
     6         int right = nums.length - 1;
     7         
     8         while(left <= right)
     9         {
    10             int mid = left + (right - left) / 2;
    11             
    12             if(nums[mid] == target)
    13                 return mid;
    14             else if(nums[mid] > target)
    15                 right = mid - 1;
    16             else
    17                 left = mid + 1;
    18         }
    19         
    20         return left;
    21         
    22         
    23     }
    24 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    Linux 文件 目录结构探索
    实践 : Ubuntu 上 Testlink 部署
    Linux 查找安装包所在目录的常用方法
    selenium + python 测试环境搭建 (WINDOWS)
    EntityFramework 学习 一 Entity Framework结构体系
    castle windsor学习-------Container Events 容器的事件
    castle windsor学习----ComponentModel construction contributors
    castle windsor学习----- CastleComponentAttribute 特性注册
    castle windsor学习-----Inline dependencies 依赖
    castle windsor学习-----Registering components by conventions
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7180118.html
Copyright © 2011-2022 走看看