zoukankan      html  css  js  c++  java
  • 5. 第k大元素

    描述

    在数组中找到第 k 大的元素。

    你可以交换数组中的元素的位置

    样例

    样例 1:

    输入:
    n = 1, nums = [1,3,4,2]
    输出:
    4
    

    样例 2:

    输入:
    n = 3, nums = [9,3,2,4,8]
    输出:
    4
    

     

     

    题解:

    public class Solution {
        /**
         * @param n: An integer
         * @param nums: An array
         * @return: the Kth largest element
         */
        public int kthLargestElement(int k, int[] nums) {
            int n = nums.length;
            // 为了方便编写代码,这里将第 k 大转换成第 k 小问题。
            k = n - k;
            return partition(nums, 0, n - 1, k);
        }
        public int partition(int[] nums, int start, int end, int k) {
            int left = start, right = end;
            int pivot = nums[left];
            
            while (left <= right) {
                while (left <= right && nums[left] < pivot) {
                    left++;
                }
                while (left <= right && nums[right] > pivot) {
                    right--;
                }
                if (left <= right) {
                    swap(nums, left, right);
                    left++;
                    right--;
                }
            }
            
            // 如果第 k 小在右侧,搜索右边的范围,否则搜索左侧。
            if (k <= right) {
                return partition(nums, start, right, k);
            }
            if (k >= left) {
                return partition(nums, left, end, k);
            }
            return nums[k];
        }
        public void swap(int[] nums, int x, int y) {
            int temp = nums[x];
            nums[x] = nums[y];
            nums[y] = temp;
        }
    }
    
  • 相关阅读:
    线程
    unix架构
    Unix命令
    可重入函数reentrant function
    Eclipse 中 program arguments 与 VM arguments 的区别
    Java中Generics的使用
    Java的Reflection机制
    Java按值传递、按引用传递
    Java label
    LeetCode Merge Intervals
  • 原文地址:https://www.cnblogs.com/deepend/p/14199250.html
Copyright © 2011-2022 走看看