zoukankan      html  css  js  c++  java
  • [LeetCode]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

    思考:二分搜索。

    class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            int left=0;
            int right=n-1;
            int mid;
            while(left<=right)
            {
                if(A[left]>target) return left;
                if(A[right]<target) return right+1;
                mid=(left+right)>>1;
                if(A[mid]==target) return mid;
                else if(A[mid]>target) right=mid-1;
                else left=mid+1;
            }
        }
    };
    

      

  • 相关阅读:
    练习12
    练习11
    练习10(图片题)
    练习9(第九章习题)
    练习8(图片题)
    练习5
    练习4
    对象的赋值与比较
    静态方法
    静态变量
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3449318.html
Copyright © 2011-2022 走看看