技术栈

C++ | Leetcode C++题解之第398题随机数索引

Ddddddd_1582024-09-11 8:33

题目:

题解:

cpp 复制代码
class Solution {
    vector<int> &nums;
public:
    Solution(vector<int> &nums) : nums(nums) {}

    int pick(int target) {
        int ans;
        for (int i = 0, cnt = 0; i < nums.size(); ++i) {
            if (nums[i] == target) {
                ++cnt; // 第 cnt 次遇到 target
                if (rand() % cnt == 0) {
                    ans = i;
                }
            }
        }
        return ans;
    }
};
上一篇:交换机vlan配置实现
下一篇:spring如何整合druid连接池?
相关推荐
樱木Plus
16 小时前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
blasit
2 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_
4 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星
4 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛
5 天前
delete又未完全delete
c++
端平入洛
6 天前
auto有时不auto
c++
琢磨先生David
7 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈2021
7 天前
信号量和信号
linux·c++
多恩Stone
7 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马
7 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
热门推荐
01GitHub 镜像站点02OpenClaw 使用和管理 MCP 完全指南03OpenClaw + 飞书(Feishu)环境搭建指南04OpenClaw优化飞书API 额度已耗尽问题05本地部署 OpenClaw + DeepSeek-R1 完全指南06Claude Code + GLM4.7 避坑指南:解决 Unable to connect to Anthropic services07小黑课堂计算机二级WPSoffice题库软件下载安装教程(2026年3月最新版)08Window 10部署openclaw报错node.exe : npm error code 12809让 Trae IDE 智能体 “读懂”文档 Excel+PDF+DOCX :mcp-documents-reader 工具使用指南10OpenClaw大龙虾机器人完整安装教程