博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]398. Random Pick Index
阅读量:2785 次
发布时间:2019-05-13

本文共 696 字,大约阅读时间需要 2 分钟。

在乱序数组中找到target的随机index,target可能重复。

时间复杂度:O(N),空间复杂度:O(1)

public class Solution {        int[] nums;    Random random;        public Solution(int[] nums) {        this.nums = nums;        this.random = new Random();    }        public int pick(int target) {        int count = 1;        int res = -1;        for (int i = 0; i < nums.length; i++) {            if (nums[i] == target) {                if (random.nextInt(count) == count - 1) {                    res = i;                }                count++;            }        }        return res;    }}/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */

转载地址:http://mahld.baihongyu.com/

你可能感兴趣的文章
vue中各种通信传值方式总结
查看>>
vuex实现及简略解析(小结)
查看>>
useradd 无法打开 /etc/passwd
查看>>
VMWare安装Centos7下载和安装教程
查看>>
CentOS 7 minimal 版本安装后网络配置
查看>>
python编程入门教程下载-Python编程从入门到实践的PDF教程免费下载
查看>>
用python画四叶草-python turtle工具绘制四叶草的实例分享
查看>>
python爬虫什么意思-Python为什么叫爬虫?Python与爬虫有什么关系?
查看>>
python代码示例-总算知道python入门代码示例
查看>>
python里怎么读取文件-python怎么读取文本文件
查看>>
python工资一般多少p-Python里的黄金库,学会了你的工资至少翻一倍
查看>>
python全套教程大全-千锋出品全套python视频教程,400大全集,你了解吗?
查看>>
python的优点有哪些-Python语言的特点有哪些
查看>>
python免费课程400节-北京市python儿童学编程
查看>>
python中文版下载-趣学python编程中文版 PDF 下载
查看>>
python入门教程pdf-python基础教程第4版pdf
查看>>
从零开始学习python编程-从0开始的Python学习014面向对象编程(推荐)
查看>>
python可以做什么-学会Python后都能做什么?网友们的回答简直不要太厉害
查看>>
2018年python工作好找吗-2018年涨工资了吗?Python 工程师薪资最新出炉
查看>>
python入门指南txt-十分钟搞定 C/C++ 项目自动化构建 —— Xmake 入门指南
查看>>