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

     1 public class Solution {
     2     public int searchInsert(int[] A, int target) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(A == null || A.length == 0 || target < A[0]) return 0;
     5         int len = A.length;
     6         for(int i = 0; i < len; i ++){
     7             if(A[i] == target){
     8                 return i;
     9             }
    10             else if(A[i] > target){
    11                 return i;
    12             }
    13         }
    14         return len;
    15     }
    16 }

     第二遍:

    采用二分来做。

     1 public class Solution {
     2     public int searchInsert(int[] A, int target) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(A == null || A.length == 0 || target < A[0]) return 0;
     5         int len = A.length;
     6         int start = 0;
     7         int end = len - 1;
     8         int ret = end;
     9         while(start <= end){
    10             int mid = (start + end) / 2;
    11             if(target == A[mid]) return mid;
    12             if(target < A[mid]){
    13                 ret = mid;
    14                 end = mid - 1;
    15             }else{
    16                 ret = mid + 1;
    17                 start = mid + 1;
    18             }
    19         }
    20         return ret;
    21     }
    22 }
  • 相关阅读:
    python斐波那契数列
    python装饰器
    Python文件操作
    python 第三方库的安装方法
    Ajax 基本使用学习记录
    微分方程概述
    Typora中的数学公式
    Ubuntu20.04 安装 mysql8.0 之后 root 账户无法登录
    Ubuntu20.04换源之后依旧慢?如何更有效的换源
    Ubuntu18.04更新python版本
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3365045.html
Copyright © 2011-2022 走看看