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 }
  • 相关阅读:
    压缩和还原压缩的JS代码
    mysql给某字段随机赋特定范围的整数值
    (五)绘制图像
    (四)旋转 缩放 位移 保存状态
    (三)描边 填充 绘制 开始路径 结束路径 绘制文本
    (二)导出图像
    (一)获取上下文绘图环境
    封装原生Ajax
    原生Ajax写法(GET)
    Angular跨域
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3365045.html
Copyright © 2011-2022 走看看