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

    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 4:

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

    有序的数组,查找固定的元素,很明显的二分查找

     1 int searchInsert(int* nums, int numsSize, int target) {
     2       /*当查找到最后,若没有找到,要是小于target,则返回index+1,
     3         若大于target,则返回target*/
     4     int low=0,high=numsSize-1;
     5     int mid,pos;
     6     while(low<=high){
     7         mid=(low+high)/2;
     8         if(nums[mid]==target)    return mid;
     9         if(nums[mid]<target)    low=mid+1;        
    10         if(nums[mid]>target)    high=mid-1;    
    11     }
    12     
    13     return nums[mid]>target?mid:mid+1;
    14 }
  • 相关阅读:
    事务 ~ 锁
    JDBC
    C# ~ 由 IDisposable 到 GC
    C# ~ 泛型委托
    函数式编程
    反射
    测试初识
    C# ~ 从 委托事件 到 观察者模式
    C# ~ 从 IEnumerable / IEnumerator 到 IEnumerable<T> / IEnumerator<T> 到 yield
    Java初识
  • 原文地址:https://www.cnblogs.com/real1587/p/9786978.html
Copyright © 2011-2022 走看看