33. Search in Rotated Sorted Array(unsolved)

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

解答:

考虑几个例子
4 5 6 7 0 1 2
2 4 5 6 7 0 1
5 6 7 0 1 2 4
6 7 0 1 2 4 5
可以发现,中间的数假如大于最右边的数,那么左边的数都是单调递增的,否则右边的数都是单调递增的。那么可以考虑单调递增的区间的最左边和最右边与target的大小·,这样就能判断出target在不在这个区间,不在的话就在另一个区间中。

class Solution {
public:
    int search(vector<int>& nums, int target) {
        int n=nums.size()-1;
        int left=0,right=n;
        while(left<=right)
        {
            int mid=(left+right)/2;
            if(nums[mid]==target) return mid;
            if(nums[mid]<nums[right])
            {
               if(nums[right]>=target&&nums[mid]<target) left=mid+1;
               else right=mid-1;
            }
            else
            {
               if(nums[left]<=target&&nums[mid]>target) right=mid-1;
               else left=mid+1;
            }
        }
        return -1;
    }
};
在Python中,并没有一个内建函数或方法叫做`.minimum_rotated_rectangle`。不过,如果你是在图像处理或计算机视觉的上下文中提到这个术语,可能是你在使用某个库或框架时接触到的函数或方法,它用于计算并返回最小旋转矩形。 在OpenCV库中,可以使用`minAreaRect()`函数来找到给定点集的最小旋转矩形。这个函数返回一个`RotatedRect`对象,包含了旋转矩形的中心点、宽度、高度以及旋转角度。最小旋转矩形是能够覆盖所有点且面积最小的矩形。 以下是一个使用OpenCV实现最小旋转矩形的例子: ```python import cv2 import numpy as np # 假设points是一个二维点集,例如 [[x1, y1], [x2, y2], ..., [xn, yn]] points = np.array([[10, 10], [10, 30], [30, 30], [30, 10]], dtype=np.float32) # 使用minAreaRect函数计算最小旋转矩形 rect = cv2.minAreaRect(points) # 输出旋转矩形的中心点、尺寸和旋转角度 print("旋转矩形的中心点:", rect[0]) print("旋转矩形的尺寸:", rect[1]) print("旋转矩形的角度:", rect[2]) # 绘制旋转矩形 box = cv2.boxPoints(rect) box = np.int0(box) cv2.drawContours(image, [box], 0, (0, 255, 0), 2) ``` 在这段代码中,首先创建了一个点集`points`,然后使用`minAreaRect()`函数计算出最小旋转矩形。`rect[0]`是旋转矩形的中心,`rect[1]`是旋转矩形的尺寸(宽度和高度),`rect[2]`是旋转矩形的角度。最后,使用`boxPoints()`函数和`drawContours()`函数将旋转矩形绘制到图像上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值