leetcode34 数组二分法 找数组中目标元素的起始和结束位置 写题笔记与收获

题目描述

给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。

如果数组中不存在目标值 target,返回 [-1, -1]

你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。

示例 1:

输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]

示例 2:

输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]

示例 3:

输入:nums = [], target = 0
输出:[-1,-1]

思路:用两个二分法分别找出左边界与右边界

收获:通过对比学习“代码随想录”官方代码,获得了以下启发

1. 用循环中的值在循环中的自然变化控制循环结束,不用多余复杂条件--巧妙设计

2. 写子函数,规范步骤。明确输出值,最后一起调整输出。(自己写的特殊条件不太有统筹规划性,容易错漏)

 “代码随想录”官方代码(C++):

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int leftBorder = getLeftBorder(nums, target);
        int rightBorder = getRightBorder(nums, target);
        // 情况一
        if (leftBorder == -2 || rightBorder == -2) return {-1, -1};
        // 情况三
        if (rightBorder - leftBorder > 1) return {leftBorder + 1, rightBorder - 1};
        // 情况二
        return {-1, -1};
    }
private:
     int getRightBorder(vector<int>& nums, int target) {
        int left = 0;
        int right = nums.size() - 1;
        int rightBorder = -2; // rightBorder没有被赋值时
        while (left <= right) {
            int middle = left + ((right - left) / 2);
            if (nums[middle] > target) { // right大小控制循环何时结束
                right = middle - 1;
            } else { 
                // 寻找右边界,nums[middle] == target的时候更新left
                left = middle + 1;
                rightBorder = left;      // (右边界用最大left找)超出一位
            }
        }
        return rightBorder;
    }
    int getLeftBorder(vector<int>& nums, int target) {
        int left = 0;
        int right = nums.size() - 1;
        int leftBorder = -2; // leftBorder没有被赋值的情况
        while (left <= right) {
            int middle = left + ((right - left) / 2);
            if (nums[middle] >= target) { 
                // 寻找左边界,nums[middle] == target的时候更新right
                right = middle - 1;
                leftBorder = right; // (左边界用最大right找)超出一位
            } else {
                left = middle + 1; // left大小控制循环结束
            }
        }
        return leftBorder;
    }
};

我的代码(python)

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        left = 0;
        right = len(nums)-1;

        # 记录左,右边界中间值的的数组,用于判断循环结束
        left_mid = []; 
        right_mid = [];

        if not nums or nums[right]<target or nums[left]>target:
            return [-1,-1];
        if len(nums) < 2:
            if nums[0]==target:
                return [0,0];
            else: return [-1,-1];
        if len(nums) == 2:
            if nums[0]==target and nums[1] == target:
                return [0,1];
            elif nums[0] == target and nums[1] != target:
                return [0,0];
            elif nums[0] != target and nums[1] == target:
                return [1,1];
            else: return [-1,-1];
        # 寻找右边界
        while left<=right:
            mid = int(left+right)/2;
            right_mid.append(mid);
            if target > nums[mid]:
                left = mid+1;
            elif  target < nums[mid]:
                right = mid-1;
            else:
                left = mid;
            if len(right_mid)>=2 and (right_mid[-1]==right_mid[-2]) and nums[mid]==target:
                if nums[mid]==nums[right]:
                    right_border = right;
                else: right_border = mid;
                break; 
            elif len(right_mid)>=2 and (right_mid[-1]==right_mid[-2]) and nums[mid]!=target: right_border = -1; break; 
            else: right_border = -1
        # 寻找左边界
        left = 0;
        right = len(nums)-1;
        while left<=right:
            mid = int(left+right)/2;
            left_mid.append(mid);
            if target > nums[mid]:
                left = mid+1;
            elif  target < nums[mid]:
                right = mid-1;
            else:
                right = mid;
            if len(left_mid)>=2 and (left_mid[-1]==left_mid[-2]) and nums[mid]==target:
                if nums[mid]==nums[left]:
                    left_border = left;
                else: left_border = mid;
                break; 
            elif len(left_mid)>=2 and (left_mid[-1]==left_mid[-2]) and nums[mid]!=target: left_border = -1; break;
            else: left_border = -1;     

        if left_border == -1 and right_border != -1:
            left_border = right_border;
        if left_border != -1 and right_border == -1:
            right_border = left_border;
        return [left_border,right_border];

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值