LeetCode Rust - 48 - 旋转图像

原题:48. 旋转图像 - 力扣(LeetCode)

解一,模拟旋转

暴力模拟,懒得写

解二,翻转两次

  1. 先沿着左下到右上的对角线左右翻转
    • 从左下角的元素开始,将该元素上方右侧的项依次交换位置
  2. 再验证水平中线上下翻转
pub fn rotate(matrix: &mut Vec<Vec<i32>>) {
	let max_index = matrix.len() - 1;
	let mut x = 0usize;
	let mut y = max_index;
	
	while x < max_index && y > 0 {
		let mut i = x + 1;
		let mut j = y - 1;
		while i <= max_index && j >= 0 {
			let tmp = matrix[y][i];
			matrix[y][i] = matrix[j][x];
			matrix[j][x] = tmp;
			if j == 0 { break; } // usize 类型为非负数,再自减会报错,手动 break
			i += 1;
			j -= 1;
		}
		x += 1;
		y -= 1;
	}

	for i in 0..max_index + 1 {
		let mut top = 0usize;
		let mut bottom = max_index;
		while top < bottom {
			let tmp = matrix[top][i];
			matrix[top][i] = matrix[bottom][i];
			matrix[bottom][i] = tmp;
			top += 1;
			bottom -= 1;
		}
	}
}

时间:$O(n^2)$

这里的 $n$ 是边长,每次翻转都要访问一遍所有元素,总共访问两次,宽松点就是 $n^2$,严格点是 $2n^2$

空间:$O(1)$

反向链接


图谱

LeetCodeObsidian我的作品技术蓝色协议(日服)FLCL无职转生~到异世界就拿出真本事~混沌武士2023-06-062023-06-102023-06-132023-07-02Antd NoteBookCPU性能天梯图CSS NoteBookGFWIndexedDB 读写地狱JS 事件循环JS 原型链JS 运算符LaTeX NoteBookLeetCode Rust - 1 - 两数之和LeetCode Rust - 122 - 买卖股票的最佳时机 IILeetCode Rust - 125 - 验证回文串LeetCode Rust - 136 - 只出现一次的数字LeetCode Rust - 189 - 轮转数组LeetCode Rust - 217 - 存在重复元素LeetCode Rust - 242 - 有效的字母异位词LeetCode Rust - 26 - 删除有序数组中的重复项LeetCode Rust - 283 - 移动零LeetCode Rust - 344 - 反转字符串LeetCode Rust - 350 - 两个数组的交集 IILeetCode Rust - 36 - 有效的数独LeetCode Rust - 387 - 字符串中的第一个唯一字符LeetCode Rust - 48 - 旋转图像LeetCode Rust - 66 - 加一LeetCode Rust - 7 - 整数反转LeetCode Rust - 8 - 字符串转换整数 (atoi)Rust NoteBookYAMLcargo 配置hugo-obsidian 元数据解析问题safari 移动端适配发布同步国际邮箱安装 mingw显卡性能天梯图注册日本邮箱科学上网第三方插件配置 Ruby 环境🤖Gmail🤖Netch🤖Obsidian Git🤖Outlook🤖Plugin Proxy🤖epub.js🤖pdf.js🤖yuè - Web 阅读器🤖加速器HomeReact18 diff 算法Vue3 diff 算法Vue3 响应式系统Vue3 渲染流程CssMarkdownReactRustViteVueWebpack下载万代南梦宫启动器下载蓝色协议注册万代南梦宫账号🤖setup CliLeetcode originLeetcode time&space