LeetCode 215. Kth Largest Element in an Array
来源:互联网 发布:mac怎么强制退出软件 编辑:程序博客网 时间:2024/06/05 10:50
问题描述
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.
题目分析
给定一个数组,找出其中第K大的数。这个题目可以先对当前数组进行排序,然后返回第K个数。也可以使用类似于快排的实现方法,快排交换都是将当一个数定位到当前数组中的某一个位置,如果这个位置就是第K大的数直接返回,如果比k大就在左边,如果比k小就在右边。
代码实现
/** * 找出nums中第k大的数 * * @param nums 当前数组 * @param k * @return */ public int findKthLargest(int[] nums, int k) { //使用快排的方式找出当前nums中第k大的数 int left = 0; int right = nums.length - 1; int index = -1; int target = k - 1; do { index = findIndexOfLeft(nums, left, right); if (index > target) { right = index - 1; } else { left = index + 1; } } while (index != target); return nums[k - 1]; } /** * nums[left]的升序放置在当前的nums中。 * * @param nums 数组 * @param left 左坐标 * @param right 右坐标 * @return 返回nums[left]在nums中升序的位置 */ protected int findIndexOfLeft(int[] nums, int left, int right) { int temp = nums[left]; while (left < right) { while (left < right && nums[right] <= temp) { right--; } if (left < right) { nums[left] = nums[right]; } while (left < right && nums[left] > temp) { left++; } if (left < right) { nums[right] = nums[left]; } } nums[left] = temp; return left; }
总结
快速排序中,每一轮的执行都会将一个数最终放到最终结果中的某一个位置。
阅读全文
0 0
- Leetcode Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- [LeetCode] Kth Largest Element in an Array
- [leetcode] Kth Largest Element in an Array
- leetcode--Kth Largest Element in an Array
- #leetcode#Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- 【Leetcode】Kth Largest Element in an Array
- Leetcode: Kth Largest Element in an Array
- Kth Largest Element in an Array -- leetcode
- [Leetcode]Kth Largest Element in an Array
- [LeetCode]Kth Largest Element in an Array
- *LeetCode-Kth Largest Element in an Array
- LeetCode----Kth Largest Element in an Array
- LeetCode Kth Largest Element in an Array
- leetcode-Kth Largest Element in an Array
- LeetCode -- Kth Largest Element in an Array
- [Python] Python与Excel--只读|只写|读写|创建图表
- This application’s application-identifier entitlement does not match that of the installed applicati
- DSP程序死机(跑飞)的一些情况-软件原因
- javaWeb-javaBean+内省机制+模拟Hibernate的CRUD操作
- python-nmap 帮助文档
- LeetCode 215. Kth Largest Element in an Array
- PTA 2.4
- 接下来要做的事
- 自定义控件View的使用
- 《CSS Mastery》 Chapter 1 问题解决
- CSS(十) 设置超链接样式
- java高级工作流,程序调优,负载均衡,Solr集群与应用,主从复制,中间件,全文检索
- 【Android学习】socket长连接,数据粘包问题
- POJ 2348 Euclid's Game 笔记