189. Rotate Array (E)

本文详细介绍了如何通过多种方法优化旋转数组的实现过程,特别是通过O(1)空间复杂度的方法,包括翻转法、暴力法、额外数组法和循环替换法,每种方法都附有代码实现,旨在提高算法效率。

Rotate Array (E)

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

题意

将给定数列的指定后半部分与前半部分换位,得到新数组。

思路

最经典的O(1)O(1)O(1)空间方法是翻转法:先将左子数组翻转,再将右子数组翻转,最后将整个数组翻转,得到的就是目标数组。

比较直接的是按照步骤一个一个移动元素,或者使用额外数组先将右子数组保存下来再处理。

官方解答还提供了一种循环替换法:以一个元素为起点,直接将该元素放在它应在的位置上,并将该位置上原本的元素继续按上述操作放在下一个位置上,直到回到起点完成一次循环,接着更换起点重复操作即可。当这种放置进行了n次后,所有元素都已经在它应在的位置上。该方法是对暴力法的一种优化。


代码实现 - 翻转法

class Solution {
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        reverse(nums, 0, nums.length - 1 - k);
        reverse(nums, nums.length - k, nums.length - 1);
        reverse(nums, 0, nums.length - 1);
    }

    private void reverse(int[] nums, int left, int right) {
        while (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++;
            right--;
        }
    }
}

代码实现 - 暴力法

class Solution {
    public void rotate(int[] nums, int k) {
        for (int i = 0; i < k; i++) {
            int pre = nums[nums.length - 1];
            for (int j = 0; j < nums.length; j++) {
                int temp = nums[j];
                nums[j] = pre;
                pre = temp;
            }
        }
    }
}

代码实现 - 额外数组

class Solution {
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        int[] temp = Arrays.copyOfRange(nums, nums.length - k, nums.length);
        for (int i = nums.length - 1; i >= k; i--) {
            nums[i] = nums[i - k];
        }
        for (int i = 0; i < k; i++) {
            nums[i] = temp[i];
        }
    }
}

代码实现 - 循环替换

class Solution {
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        int count = 0;
        
        // 当count==nums.length时,说明所有元素都已经在它应在的位置上
        for (int i = 0; count < nums.length; i++) {
            int j = i;
            int pre = nums[j];
            do {
                int next = (j + k) % nums.length;
                int temp = nums[next];
                nums[next] = pre;
                pre = temp;
                j = next;
                count++;
            } while (j != i);	// 回到起点,说明一次循环完成
        }
    }
}
import os import sys import cv2 from cv2 import resize import numpy as np import matplotlib.pyplot as plt import argparse from PIL import Image import torch import src.utils as utils import src.dataset as dataset import crnn.seq2seq as crnn def seq2seq_decode(encoder_out, decoder, decoder_input, decoder_hidden, max_length): decoded_words = [] alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZŽŠŪ-\'" converter = utils.ConvertBetweenStringAndLabel(alph) prob = 1.0 for di in range(max_length): decoder_output, decoder_hidden, decoder_attention = decoder(decoder_input, decoder_hidden, encoder_out) probs = torch.exp(decoder_output) _, topi = decoder_output.data.topk(1) ni = topi.squeeze(1) decoder_input = ni prob *= probs[:, ni] if ni == utils.EOS_TOKEN: break else: decoded_words.append(converter.decode(ni)) words = ''.join(decoded_words) prob = prob.item() return words, prob def find_median(array_vals): array_vals.sort() mid = len(array_vals) // 2 return array_vals[mid] def detect_centerline(array_vals): max_val = max(array_vals) index_list = [index for index in range(len(array_vals)) if array_vals[index] == max_val] return find_median(index_list) def rotate_image(image, angle): image_center = tuple(np.array(image.shape[1::-1]) / 2) rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0) result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR) return result def extract_peak_ranges_from_array(array_vals, minimum_val=100, minimum_range=2): start_i = None end_i = None peak_ranges = [] for i, val in enumerate(array_vals): if val >= minimum_val and start_i is None: start_i = i elif val >= minimum_val and start_i is not None: pass elif val < minimum_val and start_i is not None: end_i = i if end_i - start_i > minimum_range: peak_ranges.append((start_i, end_i)) start_i = None end_i = None elif val < minimum_val and start_i is None: pass else: raise ValueError("Cannot Parse") return peak_ranges parser = argparse.ArgumentParser() parser.add_argument('--img_path', type=str, default='', help='the path of the input image') parser.add_argument('--rot_angle', type=int, default=0, help='the global rotation image') parser.add_argument('--padding', type=int, default=10, help='paddings at the head of the image') parser.add_argument('--block_size', type=int, default=33, help='threshold for binarizing image, odd number only') parser.add_argument('--threshold', type=int, default=32, help='radius to calculate the average for thresholding, even number only') parser.add_argument('--vertical_minimum', type=int, default=800, help='minimal brightness of each VERTICAL line') parser.add_argument('--word_minimum', type=int, default=200, help='minimal brightness of each WORD') parser.add_argument('--blur', type=bool, default=False, help='apply blur to words?') parser.add_argument('--pretrained', type=int, default=1, help='which pretrained model to use') cfg = parser.parse_args() def main(): global_rot_angle = cfg.rot_angle global_padding = cfg.padding imagename = cfg.img_path if cfg.pretrained == 0: my_encoder = "./model/encoder_0.pth" my_decoder = "./model/decoder_0.pth" elif cfg.pretrained == 1: my_encoder = "./model/encoder_1.pth" my_decoder = "./model/decoder_1.pth" else: sys.exit("Unknown Pretrained Model!") print("Analyzing: "+imagename) alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZŽŠŪ-\'" print("Using Möllendorff Alphabet List: " + alphabet + "\n") # len(alphabet) + SOS_TOKEN + EOS_TOKEN num_classes = len(alphabet) + 2 transformer = dataset.ResizeNormalize(img_width=480, img_height=64) image_color = cv2.imread(imagename) image_shape = (image_color.shape[0], image_color.shape[1]) image_binary = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY) image = cv2.rotate(image_binary, cv2.ROTATE_90_COUNTERCLOCKWISE) adaptive_threshold = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, cfg.block_size, cfg.threshold) adaptive_threshold = rotate_image(adaptive_threshold, global_rot_angle) adaptive_threshold = cv2.copyMakeBorder(adaptive_threshold, 20, 20, 20, 20, cv2.BORDER_CONSTANT, 0) adaptive_threshold = adaptive_threshold[10:adaptive_threshold.shape[0]-10, 10:adaptive_threshold.shape[1]-10] image_blur = cv2.GaussianBlur(adaptive_threshold,(3,3),cv2.BORDER_DEFAULT) cv2.imshow('Binary Image', cv2.rotate(adaptive_threshold, cv2.ROTATE_90_CLOCKWISE)) cv2.waitKey(1) vertical_sum = np.sum(image_blur, axis=1) peak_ranges = extract_peak_ranges_from_array(vertical_sum,minimum_val=cfg.vertical_minimum,minimum_range=5) img_display = np.copy(adaptive_threshold) #peak_ranges.append((peak_ranges[-1][1],adaptive_threshold.shape[0])) peak_ranges.reverse() horizontal_peak_ranges2d = [] for peak_range in peak_ranges: start_y = 0 end_y = img_display.shape[1] image_x = image_blur[peak_range[0]:peak_range[1], start_y:end_y] horizontal_sum = np.sum(image_x,axis = 0) # plt.plot(horizontal_sum, range(horizontal_sum.shape[0])) # plt.gca().invert_yaxis() # plt.show() horizontal_peak_ranges = extract_peak_ranges_from_array(horizontal_sum,minimum_val=cfg.word_minimum,minimum_range=5) horizontal_peak_ranges2d.append(horizontal_peak_ranges) for hor in horizontal_peak_ranges: cv2.rectangle(img_display, (hor[0], peak_range[0]), (hor[1], peak_range[1]), 140, 1) word_piece = adaptive_threshold[peak_range[0]:peak_range[1],hor[0]:hor[1]] if cfg.blur: word_piece = cv2.GaussianBlur(word_piece,(1,1),cv2.BORDER_DEFAULT) else: pass image_dimension = (word_piece.shape[0], word_piece.shape[1]) #cv2.imshow('Words', word_piece) #print(word_piece.shape) if image_dimension[0] < 30 or image_dimension[1] < 20: pass else: factor = 1 image_resized = cv2.resize(word_piece, (int(image_dimension[1]*factor),int(image_dimension[0]*factor)), interpolation = cv2.INTER_AREA) hor_sum = np.sum(image_resized, axis=1) ctr_line = detect_centerline(hor_sum) image_dimension_new = (image_resized.shape[0], image_resized.shape[1]) add_padding = max([ctr_line, image_dimension_new[0]-ctr_line]) # cv2.imshow('current Image', image_resized) # cv2.waitKey(0) if image_dimension_new[1]<=500: padded = cv2.copyMakeBorder(image_resized, add_padding-ctr_line, add_padding-image_dimension_new[0]+ctr_line, 0, 0, cv2.BORDER_CONSTANT, 0) else: padded = image_resized factor = 64/padded.shape[0] padded = cv2.resize(padded, (int(padded.shape[1]*factor),int(padded.shape[0]*factor)), interpolation = cv2.INTER_AREA) padded = cv2.copyMakeBorder(padded, 0, 0, global_padding, 480 - global_padding - padded.shape[0], cv2.BORDER_CONSTANT, 0) padded = Image.fromarray(np.uint8(padded)).convert('L') padded = transformer(padded) padded = padded.view(1, *padded.size()) padded = torch.autograd.Variable(padded) encoder = crnn.Encoder(1, 1024) # no dropout during inference decoder = crnn.Decoder(1024, num_classes, dropout_p=0.0, max_length=121) map_location = 'cpu' encoder.load_state_dict(torch.load(my_encoder, map_location=map_location)) decoder.load_state_dict(torch.load(my_decoder, map_location=map_location)) encoder.eval() decoder.eval() encoder_out = encoder(padded) max_length = 121 decoder_input = torch.zeros(1).long() decoder_hidden = decoder.initHidden(1) words, prob = seq2seq_decode(encoder_out, decoder, decoder_input, decoder_hidden, max_length) print(words+" ", end = '') print("\n") cv2.destroyAllWindows() cv2.imshow('Current Line', cv2.rotate(img_display, cv2.ROTATE_90_CLOCKWISE)) cv2.waitKey(1) input("Reading Completed, Press Any Key to Exit. Ambula Baniha.") # color = (0, 0, 255) # for i, peak_range in enumerate(peak_ranges): # for horizontal_range in horizontal_peak_ranges2d[i]: # x = peak_range[0] # y = horizontal_range[0] # w = peak_range[1] # h = horizontal_range[1] # patch = adaptive_threshold[x:w,y:h] # cv2.rectangle(img_display, (y,x), (h,w), 255, 2) # # print(cnt) # # cv2.imwrite("/Users/zhuohuizhang/Downloads/ManchuOCR/Data/"+fontname+"/Result/"+'%d' %cnt + '.jpg', patch) # cnt += 1 # # cv2.imshow('Vertical Segmented Image', line_seg_blur) # cv2.waitKey(0) if __name__ == "__main__": main() 在该代码上进行修改,可以以图形化的方式(tkinter)展现,在保证上面代码所有功能可以正常使用的情况下可以图形化调用上面代码和参数:--img_path(该参数是必填,该选项是选择图片)、--rot_angle(旋转角度,默认是0,选填)、--padding(图形头部的填充,默认值是10,选填)、--block_size(图像二值化阈值,仅限奇数,默认值是33,选填)、--threshold(计算阈值平均值的半径,仅限偶数,默认值32,选填)、--vertical_minimum(每条垂直线的最小亮度,默认值800,选填)、--word_minimum(每个单词的最小亮度,默认值200,选填)、--blur(对文字应用模糊效果?,默认值False,选填),输入参数后点击确认即可将上述代码打印的信息显示出来,并且可以打包为exe文件
09-27
数据集介绍:电力线目标检测数据集 一、基础信息 数据集名称:电力线目标检测数据集 图片数量: 训练集:2898张图片 验证集:263张图片 测试集:138张图片 总计:3299张图片 分类类别: 类别ID: 0(电力线) 标注格式: YOLO格式,包含对象标注信息,适用于目标检测任务。 数据格式:JPEG/PNG图片,来源于空中拍摄或监控视觉。 二、适用场景 电力设施监控与巡检: 数据集支持目标检测任务,帮助构建能够自动识别和定位电力线的AI模型,用于无人机或固定摄像头巡检,提升电力设施维护效率和安全性。 能源与公用事业管理: 集成至能源管理系统中,提供实时电力线检测功能,辅助进行风险 assessment 和预防性维护,优化能源分配。 计算机视觉算法研究: 支持目标检测技术在特定领域的应用研究,促进AI在能源和公用事业行业的创新与发展。 专业培训与教育: 数据集可用于电力行业培训课程,作为工程师和技术人员学习电力线检测与识别的重要资源。 三、数据集优势 标注精准可靠: 每张图片均经过专业标注,确保电力线对象的定位准确,适用于高精度模型训练。 数据多样性丰富: 包含多种环境下的电力线图片,如空中视角,覆盖不同场景条件,提升模型的泛化能力和鲁棒性。 任务适配性强: 标注格式兼容YOLO等主流深度学习框架,便于快速集成和模型开发,支持目标检测任务的直接应用。 实用价值突出: 专注于电力线检测,为智能电网、自动化巡检和能源设施监控提供关键数据支撑,具有较高的行业应用价值。
【弹簧阻尼器】基于卡尔曼滤波弹簧质量阻尼器系统噪声测量实时状态估计研究(Matlab代码实现)内容概要:本文围绕“基于卡尔曼滤波的弹簧质量阻尼器系统噪声测量与实时状态估计”展开研究,利用Matlab代码实现对系统状态的精确估计。重点在于应用卡尔曼滤波技术处理系统中存在的噪声干扰,提升对弹簧质量阻尼器系统动态行为的实时观测能力。文中详细阐述了系统建模、噪声特性分析及卡尔曼滤波算法的设计与实现过程,展示了滤波算法在抑制测量噪声、提高状态估计精度方面的有效性。同时,该研究属于更广泛的信号处理与状态估计技术应用范畴,适用于复杂动态系统的监控与控制。; 适合人群:具备一定控制系统理论基础和Matlab编程经验的高校研究生、科研人员及工程技术人员,尤其适合从事动态系统建模、状态估计与滤波算法研究的相关人员。; 使用场景及目标:①应用于机械、航空航天、自动化等领域中对振动系统状态的高精度实时估计;②为噪声环境下的传感器数据融合与状态预测提供算法支持;③作为卡尔曼滤波算法在实际物理系统中应用的教学与科研案例。; 阅读建议:建议读者结合Matlab代码实践,深入理解系统建模与滤波器设计的关键步骤,关注噪声建模与滤波参数调优对估计性能的影响,并可进一步拓展至扩展卡尔曼滤波(EKF)或无迹卡尔曼滤波(UKF)在非线性系统中的应用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值