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

    思路:

    二分搜索,如search到则返回,否则将target与二分搜索循环终止处的数进行比较:

    二分搜索循环终止时:l==r

    当A[l] >= target时,将target插入到l之前,如line 20,之前考虑相等时将该数放在l之后,但有个test case没跑过去([1], 1 expected: 0)

    否则放在l之后

     1 public int searchInsert(int[] A, int target) {
     2         // Start typing your Java solution below
     3         // DO NOT write main() function
     4         int len = A.length;
     5         int l = 0;
     6         int r = len - 1;
     7         while(l < r){
     8             int m = (l + r) / 2;
     9             if(A[m] == target){
    10                 return m;
    11             }
    12             
    13             if(A[m] < target){
    14                 l = m + 1;
    15             } else {
    16                 r = m - 1;
    17             }
    18         }
    19         
    20         if(A[l] >= target){
    21             return l;
    22         } else {
    23             return l + 1;
    24         }
    25     }
  • 相关阅读:
    DS博客作业03--树
    DS博客作业02--栈和队列
    DS博客作业02--线性表
    c博客06-结构体&文件
    c博客作业-指针
    C语言博客作业04--数组
    C语言博客作业03--函数
    图书馆
    5-互评-OO之接口-DAO模式代码阅读及应用.xls
    DS博客作业04--图
  • 原文地址:https://www.cnblogs.com/feiling/p/3232368.html
Copyright © 2011-2022 走看看