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 }
  • 相关阅读:
    【JOI2017春季合宿】Port Facility
    LOJ504「LibreOJ β Round」ZQC 的手办
    UOJ37. 【清华集训2014】主旋律
    CF1012F Passports
    AT2370 Piling Up
    CF908G New Year and Original Order
    CF643E Bear and Destroying Subtrees
    CF183D T-shirt
    「JOISC 2016 Day 3」回转寿司
    「LibreOJ β Round #2」计算几何瞎暴力
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3365045.html
Copyright © 2011-2022 走看看