查找
查找相关典型例题
参考链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/5vu0zv/
解题思路:
哈希表
1、遍历字符串 arr ,使用哈希表统计 “各字符数量是否>1
2、再遍历字符串 arr ,在哈希表中找到首个 “数量为1的字符”,并返回。
代码:
class Solution { public: char dismantlingAction(string arr) { unordered_map<char, bool> hmap; for(char c : arr) hmap[c] = hmap.find(c) == hmap.end(); for(char c : arr) if(hmap[c]) return c; return ' '; } };
class Solution { public: int countTarget(vector<int>& scores, int target) { return helper(scores, target) - helper(scores, target - 1); } private: int helper(vector<int>& scores, int tar) { int i = 0, j = scores.size() - 1; while(i <= j) { int m = (i + j) / 2; if(scores[m] <= tar) i = m + 1; else j = m - 1; } return i; } };
排序数组中的搜索问题,首先想到 二分法 解决。
- 左子数组:records[i] = i ;
- 右子数组:records[i] != i ;
class Solution { public: int takeAttendance(vector<int>& records) { int i = 0, j = records.size() - 1; while(i <= j) { int m = (i + j) / 2; if(records[m] == m) i = m + 1; else j = m - 1; } return i; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2023-11-01 FreeRTOS(1):任务管理
2023-11-01 江科大STM32(1):第一个外设GPIO