zoukankan      html  css  js  c++  java
  • LC.35.Search Insert Position

    https://leetcode.com/problems/search-insert-position/description/
    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.

    Example 1:

    Input: [1,3,5,6], 5
    Output: 2
    Example 2:

    Input: [1,3,5,6], 2
    Output: 1
    Example 3:

    Input: [1,3,5,6], 7
    Output: 4
    Example 1:

    Input: [1,3,5,6], 0
    Output: 0

    time complexity: o(logn)
    space complexity: o(1)

     1     public int searchInsert(int[] nums, int target) {
     2         if (nums == null || nums.length ==0) return 0 ;
     3         int left = 0, right = nums.length -1 ;
     4         //corner case:
     5         if (nums[left]>target){
     6             return left ;
     7         }
     8         if (nums[right]<target){
     9             return right + 1 ;
    10         }
    11         while(left + 1 < right){
    12             int mid = left + (right - left )/2 ;
    13             if (nums[mid] == target) return mid ;
    14             else if(nums[mid]<target){
    15                 left = mid ;
    16             } else {
    17                 right = mid ;
    18             }
    19         }
    20         //== now: 1) still have not found it 2) left and right sits right next to each other
    21         //post processing
    22         if (nums[left] == target) {
    23             return left ;
    24         }
    25         if (nums[right] == target){
    26             return right;
    27         }
    28         //remember left and right next to each other
    29         if(nums[left]<target && target < nums[right]){
    30             return left + 1 ;
    31         }
    32         return -1 ;
    33     }



  • 相关阅读:
    C#选择文件、选择文件夹、打开文件
    如何去掉数据库重复记录并且只保留一条记录
    SQL总结——存储过程
    SQL Server中的标识列
    c# 获取键盘的输入
    C# 中BindingSource 的用法
    WinForm timer 控件
    C#获得窗口控件句柄
    checkedListBox的使用
    c++从文件中读取特定字符串问题的总结
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8587035.html
Copyright © 2011-2022 走看看