LeetCode 215:Kth Largest Element in an Array

leetcode215数组中的第K个最大元素,python 代码+思路 """ 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2: 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4 说明:你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。 """ ''' 思考: 创建一个k长度的最小堆。然后先放进去k个,然后大于于堆顶就替换 ''' import heapq # 在这里顺便复习python堆的用法 # heappush(heap, x) 将x压入堆中 # heappop 立即下载

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


代码如下:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        int length = nums.size();
        if (length == 1) {
            return nums[0];
        }
        vector<int> left;
        vector<int> right;
        
        for (int index=1; index<length; index++) {
            if (nums[index] > nums[0]) {
                right.push_back(nums[index]);
            }else{
                left.push_back(nums[index]);
            }
        }
        length = right.size();
        if (length >=k) {
            return findKthLargest(right, k);
        }else if(length == k-1){
            return nums[0];
        }else{
            return findKthLargest(left, k-length-1);
        }
    }
};

LeetCode对时间要求不高,下面这样的代码也能通过:

class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        reverse(nums.begin(), nums.end());
        return nums[k-1];
    }
};



基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的零售柜商品检测软件(Python+PySide6界面+训练代码) 随着新零售概念的兴起,无人零售柜、智能零售店等新型零售模式快速发展。传统零售柜依赖于人工盘点和补货,效率低下且成本高昂。本文提出了一种基于YOLO系列目标检测算法的零售柜商品检测系统,实现了对零售柜内商品的自动识别、计数和库存管理。系统采用PySide6开发用户界面,集成了YOLOv5、YOLOv6、YOLOv7和YOLOv8等多种先进的深度学习模型,提供了完整的训练和推理流程。本文将详细介绍系统设计、算法实现、数据集构建和实际应用效果,并提供完整的代码实现。 阅读详情

相关推荐

揭秘Outlook/QQ邮箱伪造:如何利用Unicode编码绕过SPF检测

本文深入剖析了利用Unicode编码进行邮件显示名伪造的攻击手法,揭示了攻击者如何通过插入零宽字符等特殊编码绕过SPF检测,使邮件在Outlook、QQ邮箱等客户端中看似来自可信发件人。文章通过Python代码示例演示了伪造过程,并提供了从用户自查到管理员部署DMARC策略的多层次防御建议。

weixin_29063035的博客 338

【算法】Leetcode第215题快速排序内部原理分析(C++)

1.前言 LeetCode第215题目为数组中的第K个最大元素,这个题目可以用库函数sort直接排序然后完成。 sort(nums.begin(), nums.end()); return nums[nums.size() - k]; sort函数原理是快速排序,接下来去探究一下这个算法的本质。 快速排序是由C.A.R Hoare在1960年发明的,快速排序可能是应用最广泛的排序算法了,如它名字所述,该算法的特点就是快,一般时间复杂度是O(nlgn),但是在某些特殊情况下,时间复杂度会达到(n²)。 2

wuwenbin12的博客 2330

保姆级教程:用MATLAB搞定运动模糊图片修复(附完整代码与避坑指南)

本文提供了一份详细的MATLAB运动模糊图片修复教程,涵盖盲复原、图像复原等核心技术。通过傅里叶变换和Radon变换分析模糊参数,对比逆滤波、维纳滤波和Lucy-Richardson算法效果,并附完整代码与避坑指南,帮助用户实现专业级图像处理。

weixin_26765363的博客 236

LeetCode第 215 题:数组中的第K个最大元素(C++)

215. 数组中的第K个最大元素 - 力扣(LeetCode) 文章目录暴力排序借助堆快速排序partition随机初始化 pivot 元素三数取中法 暴力排序 既然是排序后的第k个最大的元素,那自然就会想到排序了… class Solution { public: int findKthLargest(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); return *(nums

zj 977

TK抓包协议分析:So层逆向

第三个参数是一个回调函数,这里他的返回值1表示成功,0表示失败,那我们手动把他Hook为0,让他不支持quic协议,实现降级。等,我们是为了解决抓包问题,那很有可能是在net目录下(network),那来搜索一下。开了抓包以后APP直接是网络无连接了,并且抓到的请求也是不正常的,下面我们就开始定位。看了半天感觉也没啥有用的东西,那下面我们整理一下已经有信息,来猜测一下,后续怎么进行。那可以猜测,我们真正需要Hook的那个函数也有可能是这样加载的,可以字符串搜索一下。

2503_90751938的博客 3431

拆解一个带主动均衡的BMS模块:从变压器、MOS管矩阵到控制逻辑,图文详解内部设计与成本构成

本文深度拆解了一款带主动均衡功能的BMS模块,详细解析了其核心架构、元器件选型与成本构成。通过高频变压器、MOS管矩阵等硬件设计,该模块实现了高达87%的能量转移效率,远超普通被动均衡方案。文章还揭示了汽车级PCB设计、软件策略优化等关键技术细节,为锂电池管理系统设计提供了实用参考。

weixin_42638178的博客 354

线性表操作集(c语言)

线性表操作集 顺序存储 typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; }; /* 初始化 */ List MakeEmpty() { List L; L = (List)malloc(sizeof(struct LNode)); L->Last = -1; return L;

photoresist的博客 377

Prism 入门02,区域介绍

什么是区域(Region)?区域,在Prism 框架中,区域是模块化的核心的功能之一,其主要作用是降低应用程序和模块之间的耦合度。使用方式:在应用程序的界面中,划分出某块区域,并为这个区域定义一个唯一的区域名称。那么通过这个区域名称,应用程序就可以找到指定的区域。并为这个区域动态放置一些容器或控件,从而呈现在界面中。

build2024 1128

LeetCode:215. 数组中的第K个最大元素——快速排序

🍎道阻且长,行则将至。🍓!!!LeetCode:215. 数组中的第K个最大元素。 本题也同时分析了排序算法:冒泡排序、快速排序,以及如何使用快速思想来简化解决这个问题。最后还有一个使用数组的方法来处理。

Super algorithm 的博客,技术爱好者。 2154

华为OD机试真题 新系统2026-04-08 C++ 实现【直捣黄龙】

小王在玩一款叫做直捣黄龙的小游戏,在该游戏中他需要从入口位置进入敌营,绕过哨兵的层层封锁,达到敌军司令部实施斩首行动。 敌军阵营是一个n*n的矩阵,入口在坐标(0,n/2),敌军司令部在坐标(n-1,n/2),每个 哨兵警戒以自己为中心的9宫格,一旦被哨兵发现则行动失败。

MISAYAONE的博客 270

Python 爬虫实战:爬取哔哩哔哩知识区,抓取高赞课程信息

哔哩哔哩(Bilibili)是一个广受欢迎的综合性视频社区,其中的知识区汇聚了大量优质的教育、科普、技术等课程内容。本文将指导读者如何使用 Python 爬虫技术从哔哩哔哩知识区抓取高赞课程信息,并进行数据分析。本文深入探究了利用 Python 爬虫技术从哔哩哔哩知识区抓取高赞课程信息的全流程。从前期的环境搭建、模拟登录,到核心的课程数据抓取、存储,再到后续的数据分析与可视化,都详细展开讲解并提供代码支持。通过此方法所获取的数据,能够助力创作者优化内容、用户发现优质课程、平台洞察用户需求。

u014481728的博客 1141

【LeetCode】215.数组中的第K个最大元素(三种方法,九个思路的代码实现,java格式)

题目 题目链接 解析 这道题据说是面试的高频考题,同时也是基础算法的应用。 方法一:暴力解法 题目要求我们找到“数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素” , 语义是从右边往左边数第 k 个元素(从 11 开始),那么从左向右数是第几个呢,我们列出几个找找规律就好了。 一共 6 个元素,找第 2 大,索引是 4; 一共 6 个元素,找第 4 大,索引是 2。 因此,升序排序以后,目标元素的索引是 len - k。这是最简单的思路,如果只答这个方法,面试官可能并不会满意,但是在我们

Viper的程序员修炼手册 2982

HTML5+CSS3+JS小实例:焦点图波浪切换动画特效

实例:焦点图波浪切换动画特效。字体图标库:Font Awesome。技术栈:HTML+CSS+JS。

艾恩小灰灰的博客 915

LeetCode215:Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.For example, Given [3,2,1,5,6,4] and k = 2, return 5.Note:

2583

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

leetcode 215: Kth Largest Element in an Array

leetcode 215: Kth Largest Element in an Array

西施豆腐渣 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

力扣215:数组中的第K个最大元素 (leetcode 215:Kth Largest Element In An Array)

力扣215:数组中的第K个最大元素 (leetcode 215:Kth Largest Element In An Array)

xxxnnn1991的博客 461

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Leetcode215: Kth Largest Element in an Array

215. Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For e

~\(≧▽≦)/~ 359

Leetcode 215: Find Kth Largest Element in an array

题目: Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: ...

小猪爱拱地 308

LeetCode解题分享:215. Kth Largest Element in an Array

Problem Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output:...

DaVinciL的博客 582

LeetCode:215. Kth Largest Element in an Array

Medium Find thekth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4.

叶现一的专栏 159

leetCode:215. Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2, return 5.

u011514185的专栏 310

LeetCode:215. Kth Largest Element in an Array

LeetCode:215. Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1:...

Wisimer 192

LeetCode215:Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 E...

卷卷萌的博客 287

LeetCode:215. Kth Largest Element in an Array - Python

问题描述:数组中的第K个最大元素在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。示例 1:输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 示例 2:输入: [3,2,3,1,2,4,5,5,6] 和 k = 4 输出: 4说明: 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。问题分析:这个题目...

Growth Diary 3075

Leetcode解题报告:215. Kth Largest Element in an Array

题目大意: Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. For example, Given [3,2,1,5,6,4] and k = 2,

wengyunpeng的博客 354

LeetCode: 215. Kth Largest Element in an Array 数组中第k大元素

试题: Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Ex...

心之所向 313
上一篇: LeetCode 145:Binary Tree Postorder Traversal(后序遍历)
下一篇: LeetCode 21:Merge Two Sorted Lists
「已注销」
博客等级 码龄22年 87粉丝 98原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值