7.28 进制交换|迭代器模式|map|子集按位或|带参递归

📅 发布时间:2026/7/13 3:09:56 👁️ 浏览次数:
7.28 进制交换|迭代器模式|map|子集按位或|带参递归
lc701.二叉搜索树插入void dfs不行TreeNode* dfs带接受参数处理的dfs当为空的时候就可以添加插入if (!root){return new TreeNode(val);}插入位置root-left insertIntoBST(root-left, val);class Solution {public:TreeNode* insertIntoBST(TreeNode* root, int val){// 若根节点为空直接创建新节点作为根if (!root){return new TreeNode(val);}// 根据值的大小决定插入左子树还是右子树if (val root-val){root-left insertIntoBST(root-left, val);}else{root-right insertIntoBST(root-right, val);}return root;}};联想有序合并两个链表l1-nextmerge(l1-next,l2);return l1;lc61.链表分割点class Solution {public:ListNode* rotateRight(ListNode* head, int k) {if(!head || !head-next)return head;int n0;ListNode* tmphead;while(tmp){n;tmptmp-next;}kk%n;if(k0) return head;ListNode* cyhead;int flagn-k;int cnt0;ListNode* a;ListNode* b;while(head){cnt;if(cntflag){ahead;bhead-next;break;}headhead-next;}a-nextnullptr;ListNode* newheadb;while(b-next){bb-next;}b-nextcy;return newhead;}};迭代器对比于for循环for循环一般是以特定顺序循环迭代器是以特定遍历规则去访问集合中每个元素不严谨地来说可以认为for的概念范围比迭代器小参考 迭代器模式不能用for循环遍历一个 红黑树 或hash链表之类迭代器是对所有可遍历数据结构的抽象和封装。map在C中 std::map 是有序集合其内部通过红黑树实现会按照键key的升序自动排序。获取 std::map 最后一个元素的方法- 使用 rbegin() 函数它返回指向最后一个元素的反向迭代器例如auto last map.rbegin();- 通过 *last 可访问该元素键值对通过 last-first 获取键last-second 获取值。lc82.链表删重引入flagreturn前处理newhead-nextnullptr; //截断尾部可能的残留class Solution {public:ListNode* deleteDuplicates(ListNode* head){if(!head || !head-next)return head;ListNode* newheadnew ListNode(0);ListNode* retnewhead;int flag-1000;while(head){if(head-next head-valhead-next-val)flaghead-val;if(head-val!flag){newhead-nexthead;newheadnewhead-next;}headhead-next;}newhead-nextnullptr; //截断尾部可能的残留return ret-next;}};lc190 位运算class Solution {public:uint32_t reverseBits(uint32_t n) {uint32_t result 0;for (int i 0; i 32; i)result (result 1) (n i 1);return result;}};lc2044.子集按位或计算最大按位或的子集数量class Solution {public:int countMaxOrSubsets(vectorint nums) {int max_or 0;int count 0;int n nums.size();// 遍历所有子集共2^n个for (int mask 1; mask (1 n); mask) {int current_or 0;for (int i 0; i n; i) {if (mask (1 i)) {current_or | nums[i];}}// 更新最大或值和计数if (current_or max_or){max_or current_or;count 1;}else if (current_or max_or){count;}}return count;}};主要修改说明1.聚焦子集按位或计算2. 使用位运算遍历所有非空子集掩码 mask 从1开始避免空集3. 计算每个子集的按位或值追踪最大值并统计出现次数4. 时间复杂度O(n·2ⁿ)适用于n≤20的场景题目隐含约束