LeetCode -数组数据的插入位置(二分法)

搜索数组数据插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。数组可能有重复数据,有重复数据时返回,插入到重复数据的第一个位置。

示例 1: 输入: [1,3,6,7], 5, 输出: 2
示例 1: 输入: [1,3,3,3,5,6], 3, 输出: 1

分析:改进的二分法计算 mid 时需要技巧防止溢出,即 mid=left+(right-left)/2 参考链接

class Solution {
public:
	int searchInsert(vector<int>& nums, int target) {
		int length = nums.size();
		int left = 0;
		int right = length;
		 //[3,5,7,9,10] 8        3
		while (left <right) {
			int mid = (right + left) / 2; //  2  3
			if(target > nums[mid])
			{
				left = mid+1;   //   3 4   
			}
			else {
				right = mid; //    33
			}
		}
		return left;

	}
};

在排序数组中查找元素的第一个和最后一个位置

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。你的算法时间复杂度必须是 O(log n) 级别。如果数组中不存在目标值,返回 [-1, -1]。

示例 1: 输入: nums = [5,7,7,8,8,10], target = 8。输出: [3,4]
示例 2: 输入: nums = [5,7,7,8,8,10], target = 6。输出: [-1,-1]

分析: 参考链接

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res(2,-1);
        if(nums.empty()) return res;
        int n=nums.size(),l=0,r=n;
        while(l<r){
            int m=l+(r-l)/2;
            if(nums[m]>=target) r=m;
            else l=m+1;
        }
        // target 比所有数都大
		if (l == n) return res;
        if(nums[l]!=target) return res;
        res[0]=l;
        r=n;
        while(l<r){
            int m=l+(r-l)/2;
            if(nums[m]<=target) l=m+1;
            else r=m;
        }
        res[1]=l-1;
        return res;
    }
};
发布了76 篇原创文章 · 获赞 6 · 访问量 2764

猜你喜欢

转载自blog.csdn.net/u014618114/article/details/104406095