数组中的第K个最大元素
2022-03-08 本文已影响0人
叫我颜先生
/*
- @Author: sumBorn
- @Date: 2022-02-23 19:15:51
- @LastEditTime: 2022-02-23 19:30:33
- @Description: https://leetcode-cn.com/leetbook/read/all-about-array/x90rpm/
*/
/**
-
@description: 先排序,之后输出
-
@param {*}
-
@return {*}
*/
public class Solution
{
public int FindKthLargest(int[] nums, int k)
{
for (var i = 0; i < nums.Length; i++)
{
for (var j = i + 1; j < nums.Length; j++)
{
if (nums[i] > nums[j])
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
}return nums[nums.Length - k];
}
}
/**
-
@description: 从大到小排序,排到第k-1个就停
-
@param {*}
-
@return {*}
*/
public class Solution
{
public int FindKthLargest(int[] nums, int k)
{
for (var i = 0; i < nums.Length; i++)
{
for (var j = i + 1; j < nums.Length; j++)
{
if (nums[i] < nums[j])
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}if (i == k - 1) { return nums[i]; } } return nums[nums.Length - 1];
}
}