Create Maximum Number 拼接最大数

本文介绍了一种算法,用于从两个数字数组中选取k个数字,保持原数组相对顺序,拼接成最大可能的数。通过贪心算法和栈结构,实现时间和空间效率优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定长度分别为 m 和 n 的两个数组,其元素由 0-9 构成,表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n) 个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。

求满足该条件的最大数。结果返回一个表示该最大数的长度为 k 的数组。

说明: 请尽可能地优化你算法的时间和空间复杂度。

示例 1:

输入:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
输出:
[9, 8, 6, 5, 3]

示例 2:

输入:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
输出:
[6, 7, 6, 0, 4]

示例 3:

输入:
nums1 = [3, 9]
nums2 = [8, 9]
k = 3
输出:
[9, 8, 9]

思路:这是一篇转载的文章,源博客为:https://www.cnblogs.com/CarryPotMan/p/5384172.html

主要是这篇博客讲的太详细了,已经没有需要补充的地方了。只是具体的实现有些函数不一样。

这个问题是要将两个数组合成一个数,我们先得解决一个简单一点的问题————从一个数组里挑出k个数字组成最大的数。

第一步

这个问题可以借助栈和贪心算法来实现。算法步骤:

  • 新建一个空栈stack
  • 遍历数组 nums
    • 弹出栈顶元素如果栈顶元素比nums[i]小,直到
      1、栈空
      2、剩余的数组不足以填满栈至 k
    • 如果栈的大小小于 k ,则压入nums[i]
  • 返回栈stack
    因为栈的长度知道是k,所以可以用数组来实现这个栈。时间复杂度为O(n),因为每个元素最多被push和pop一次。
    实现代码如下:
vector<int> maxArray(vector<int>& nums, int k){
    int n = nums.size();
    vector<int> result(k);
    for (int i = 0, j = 0; i < n; i++){
        while (n - i + j>k && j > 0 && result[j-1] < nums[i]) j--;
        if (j < k) result[j++] = nums[i];
    }
    return result;
}

第二步

给定两个数组,长度分别为m 和n,要得到 k = m+n的最大数。
显然这个问题是原问题的特殊情况,显然这种情况下,我们首先想到的是贪心算法。
我们要做k次选择,每次我们就选两个数组中较大的那个数即可。这是显然的,但是如果两个数相等,我们应该选择哪个呢?
这就不是很显然的了,举个栗子,

nums1 = [6,7]
nums2 = [6,0,4]
k = 5
ans = [6,7,6,0,4]

所以相等的情况,我们就需要一直往后比,直到它们不相等分出大小为止。这就有点像归并排序中的merge函数了。因为每次都得一直往后比,所以时间复杂度是O(mn)。
这部分代码如下:

bool greater(vector<int>& nums1, int i, vector<int>& nums2, int j){
    while (i < nums1.size() && j < nums2.size() && nums1[i] == nums2[j]){
        i++;
        j++;
    }
    return j == nums2.size() || (i<nums1.size() && nums1[i] > nums2[j]);
}

vector<int> merge(vector<int>& nums1, vector<int>& nums2, int k) {
    std::vector<int> ans(k);
    int i = 0, j = 0;
    for (int r = 0; r<k; r++){
        if( greater(nums1, i, nums2, j) ) ans[r] = nums1[i++] ;
        else ans[r] = nums2[j++];
    }
    return ans;
}

第三步

让我们回到原问题,我们首先把k个数分成两部分,i 和 k-i,我们可以用第一步中的函数求出两个数组中的长度为 i 和 k-i 的最大值。然后用第二步的方法将它们融合。最后我们从所有的结果中找出最大值。所以代码如下:

vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
    int m = nums1.size();
    int n = nums2.size();
    vector<int> result(k);
    for (int i = std::max(0 , k - n); i <= k && i <= m; i++){
        auto v1 = maxArray(nums1, i);
        auto v2 = maxArray(nums2, k - i);
        vector<int> candidate = merge(v1, v2, k);
        if (greater(candidate, 0, result, 0)) result = candidate;
    }
    return result;
}

参考代码:

class Solution {
public:
vector<int> selectKNumber(vector<int> nums, int k) {
	vector<int> res;
	if (!k) {
		res = nums;
		return res;
	}
	int m = nums.size() - k;
	int n = m;
	for (auto num : nums) {
		while (!res.empty() && n > 0 && res.back() < num) {
			n--;
			res.pop_back();
		}
		res.push_back(num);
	}
	while (!res[0]) res.erase(res.begin());
	while (res.size() != (nums.size() - m)) res.erase(res.end() - 1);
	return res;
}
bool isGreater(vector<int> nums1,int i, vector<int> nums2,int j) {
	while (i < nums1.size() && j < nums2.size() && nums1[i] == nums2[j]) {
		i++;
		j++;
	}
	return j == nums2.size() || (i<nums1.size() && nums1[i]>nums2[j]);
}

vector<int> merge(vector<int> nums1, vector<int> nums2, int k) {
	vector<int> res(k);
	int i =0, j = 0;
	for (int r = 0; r < k; r++) {
		if (isGreater(nums1, i, nums2, j)) res[r] = nums1[i++];
		else res[r] = nums2[j++];
	}
	return res;
}
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
	vector<int> res(k, 0);
	int m = nums1.size();
	int n = nums2.size();
	for (int i = max(0, k - n); i <= m && i <= k; i++) {
		auto v1 = selectKNumber(nums1, i);
		auto v2 = selectKNumber(nums2, k-i);
		vector<int> tmp = merge(v1, v2, k);
		if (isGreater(tmp, 0, res, 0)) res = tmp;
	}
	return res;
}
};

 

实现环绕一周视频抽帧生成全景图拼接的方法如下: 1. 使用视频处理库(如FFmpeg)读取视频文件并抽取每秒一帧的图像。 2. 对于每个抽帧得到的图像,使用图像处理库(如OpenCV)进行预处理,包括将图像转换为灰度图像、进行直方图均衡化、使用SIFT或SURF进行特征提取等。 3. 对于每个图像,计算其与前后几帧图像的相似度,选择最相似的几帧进行全景图像拼接。 4. 对于每个选定的图像,使用图像拼接库(如OpenCV的Stitcher)进行全景图像的拼接。 5. 将拼接得到的全景图像输出为文件。 下面是Python代码的示例: ``` python import cv2 import numpy as np import argparse # 构建命令行参数解析器 ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", required=True, help="path to input video file") ap.add_argument("-o", "--output", required=True, help="path to output panorama file") ap.add_argument("-f", "--frames", type=int, default=24, help="number of frames to extract per second") ap.add_argument("-s", "--similarity", type=float, default=0.5, help="minimum similarity score for matching features") ap.add_argument("-i", "--iterations", type=int, default=1000, help="maximum number of iterations for RANSAC") args = vars(ap.parse_args()) # 读取视频文件并抽取每秒一帧的图像 cap = cv2.VideoCapture(args["video"]) frames = [] while True: ret, frame = cap.read() if not ret: break if len(frames) % args["frames"] == 0: frames.append(frame) cap.release() # 对每个抽帧得到的图像进行预处理 gray_frames = [] for frame in frames: gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray_frame = cv2.equalizeHist(gray_frame) gray_frames.append(gray_frame) # 对于每个图像,计算其与前后几帧图像的相似度,选择最相似的几帧进行全景图像拼接 features = cv2.SIFT_create() matcher = cv2.BFMatcher() matches = [] for i in range(len(gray_frames)): if i == 0: matches.append([]) continue prev_gray = gray_frames[i-1] curr_gray = gray_frames[i] prev_kps, prev_descs = features.detectAndCompute(prev_gray, None) curr_kps, curr_descs = features.detectAndCompute(curr_gray, None) if prev_descs is None or curr_descs is None: matches.append([]) continue raw_matches = matcher.knnMatch(prev_descs, curr_descs, k=2) good_matches = [] for m in raw_matches: if len(m) == 2 and m[0].distance < args["similarity"] * m[1].distance: good_matches.append((m[0].queryIdx, m[0].trainIdx)) if len(good_matches) < 4: matches.append([]) continue prev_pts = np.float32([prev_kps[i].pt for (i, _) in good_matches]) curr_pts = np.float32([curr_kps[j].pt for (_, j) in good_matches]) (H, status) = cv2.findHomography(curr_pts, prev_pts, cv2.RANSAC, args["iterations"]) matches.append((H, prev_gray)) # 对于每个选定的图像,使用图像拼接库进行全景图像的拼接 stitcher = cv2.createStitcher() if imutils.is_cv3() else cv2.Stitcher_create() result = gray_frames[0] for i in range(1, len(matches)): if matches[i]: (H, prev_gray) = matches[i] result = cv2.warpPerspective(prev_gray, H, (result.shape[1] + prev_gray.shape[1], result.shape[0])) result[0:prev_gray.shape[0], 0:prev_gray.shape[1]] = prev_gray result = cv2.cvtColor(result, cv2.COLOR_GRAY2BGR) # 将拼接得到的全景图像输出为文件 cv2.imwrite(args["output"], result) ``` 这段代码实现了对视频文件进行抽帧、预处理、特征提取、相似度匹配、全景图像拼接和输出的过程。需要安装OpenCV和imutils库。其中,通过命令行参数解析器可以指定输入视频文件的路径、输出全景图像的路径、每秒抽取的帧数、特征匹配的相似度阈值和RANSAC算法的迭代次数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值