腾讯精选练习 50 题 Day14
题目:215. 数组中的第K个最大元素
来源:力扣(LeetCode) https://leetcode-cn.com/problems/kth-largest-element-in-an-array/
【中等】在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
解题思路
本题主要考察对排序算法的理解,所以最好不要调用排序JAVA自带函数。
以下为【快速排序】的代码,参考自官方题解。
执行代码
class Solution {
private Random random = new Random();
public int findKthLargest(int[] nums, int k) {
return quickSelect(nums, 0, nums.length-1, nums.length-k);
}
/*
* 按从小到大排序时,如果一次排序确定的最终位置是我们要找的位置,直接返回其值;
* 如果排序确定的最终位置小,则在其右边找
* 如果排序确定的最终位置大,则在其左边找
*/
public int quickSelect(int[] nums, int start, int end, int index) {
int i = randomPartition(nums, start, end);
if (i == index) {
return nums[i];
} else {
return i < index ? quickSelect(nums, i+1, end, index) : quickSelect(nums, start, i-1, index);
}
}
// 随机找出基准位置i,然后交换放到end下标位置处
public int randomPartition(int[] nums, int start, int end) {
int i = random.nextInt(end-start+1) + start;
swap(nums, i, end);
return partition(nums, start, end);
}
// 从小到大排序
public int partition(int[] nums, int start, int end) {
int x = nums[end];
int i = start - 1;
for (int j = start; j < end; j++) {
if (nums[j] <= x) {
i++;
swap(nums, i, j);
}
}
swap(nums, i+1, end);
return i+1;
}
public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
复杂度
时间复杂度:O( n )
空间复杂度:O( log(n) )
题目:217. 存在重复元素
简单,不做题解。
题目:230. 二叉搜索树中第K小的元素
来源:力扣(LeetCode)https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
【中等】给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
进阶:如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 1
解题思路
【中序遍历】
- 递归实现,用Min记住最小值,以及用k来计数。就可实现线性时间复杂度和常数空间复杂度。
- 如果需要经常修改和频繁查询,则可维护一个最小数的数组,查询的时候可直接查表。
执行代码
import java.util.*;
class Solution {
int k,min;
public int kthSmallest(TreeNode root, int k) {
this.k = k;
biuld_min(root);
return min;
}
public void biuld_min(TreeNode root){
if(root == null) return;
biuld_min(root.left);
if(k == 0) return; //找到最小值后,提前结束
k--;
if(k == 0) min = root.val; //记录最小值
biuld_min(root.right);
}
}
复杂度
时间复杂度:O( n )
空间复杂度:O( 1 )