• leetcode: Search Insert Position


    http://oj.leetcode.com/problems/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

    思路

    用二分法,如果能找到target,直接在当前位置插入即可,如果不能找到,根据中断循环时A[mid]的值,有以下两种情况:

    1. A[mid] < target:根据二分法的原则,mid位置上的数肯定是最后一个小于target的数,那么插入位置就是mid + 1。
    2. A[mid] > target:同理,mid位置上的数肯定是第一个大于target的数,那么插入位置就是mid。
     1 class Solution {
     2 public:
     3     int searchInsert(int A[], int n, int target) {
     4         int start = 0, end = n - 1, mid;
     5 
     6         while (start <= end) {
     7             mid = (start + end) / 2;
     8             
     9             if (A[mid] == target) {
    10                 return mid;
    11             }
    12             else if (A[mid] < target) {
    13                 start = mid + 1;
    14             }
    15             else {
    16                 end = mid - 1;
    17             }
    18         }
    19 
    20         return (A[mid] > target) ? mid : mid + 1;
    21     }
    22 };
  • 相关阅读:
    npm包开发与发布
    mapbox展示动态图标
    axios并行请求
    Vue引入ES5的js库
    git常用操作
    单词倒排
    FT232RL芯片USB转TTL应用
    应用GL823芯片自制的读卡器
    队列图示
    队列
  • 原文地址:https://www.cnblogs.com/panda_lin/p/search_insert_position.html
Copyright © 2020-2023  润新知