查找
查找相关典型例题

参考链接: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; } };

浙公网安备 33010602011771号