二叉搜索的算法

来源:互联网 发布:企业微信管理系统源码 编辑:程序博客网 时间:2024/05/29 12:46

四道在旋转数组中找最小值和 特定值的问题。

在两个有序数组中找中值的问题,leetcode 4

实现: 除法、指数、平方根 运算

Search Insert Position

 Total Accepted: 67950 Total Submissions: 192094My Submissions

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(vector<int>& nums, int target) {
        int left=0;
        int right=nums.size()-1;
        while(left<=right)
        {
            int mid=left+(right-left)/2;
            if(nums[mid]<target)
               left=mid+1;
            else if(nums[mid]>target)
               right=mid-1;
            else 
              return mid;
        }
        return left;
    }
};
第二中写法
class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        int left=0;
        int right=nums.size();
        while(left<right)
        {
            int mid=left+(right-left)/2;
            if(nums[mid]<target)
               left=mid+1;
            else if(nums[mid]>target)
               right=mid;
            else 
              return mid;
        }
        return left;
    }
};

其中 是对应的

right =n- 1;

while(left<=right)

right=mid-1;


right=n;

while(left<right)

right=mid;


0 0
原创粉丝点击