查找

查找相关典型例题

 参考链接: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[ii ;
  • 右子数组: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;
    }
};
复制代码

 

posted @   xsgcumt  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2023-11-01 FreeRTOS(1):任务管理
2023-11-01 江科大STM32(1):第一个外设GPIO
点击右上角即可分享
微信分享提示