zoukankan      html  css  js  c++  java
  • Search Insert Position 解答

    Question

    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

    Solution 1 -- Naive

    Iterate the array and compare target with ith and (i+1)th element. Time complexity O(n).

     1 public class Solution {
     2     public int searchInsert(int[] nums, int target) {
     3         if(nums==null) return 0;
     4         if(target <= nums[0]) return 0;
     5         for(int i=0; i<nums.length-1; i++){
     6             if(target > nums[i] && target <= nums[i+1]){
     7                 return i+1;
     8             }
     9         }
    10         return nums.length;
    11     }
    12 }

    Solution 2 -- Binary Search

    If the target number doesn't exist in original array, then after iteration, it must be pointed by low pointer.

    Time complexity O(log(n))

     1 public class Solution {
     2     public int searchInsert(int[] nums, int target) {
     3         if (nums == null || nums.length == 0)
     4             return 0;
     5         int start = 0, end = nums.length - 1, mid = (end - start) / 2 + start;
     6         while (start <= end) {
     7             mid = (end - start) / 2 + start;
     8             if (nums[mid] == target)
     9                 return mid;
    10             else if (nums[mid] < target)
    11                 start = mid + 1;
    12             else
    13                 end = mid - 1;
    14         }
    15         return start;
    16     }
    17 }
  • 相关阅读:
    华强北三代悦虎1562A怎么样?
    改丝印的假华强北三代1562A,用芯良苦!
    华强北三代过软件检测的佳和1562A
    Unlua静态导出
    Unlua编程基础
    Android JNI调用
    手机屏幕参数
    UE4 stats性能埋点
    【JWT】JSON Web Token
    【算法】一致性哈希算法实现
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4804009.html
Copyright © 2011-2022 走看看