zoukankan      html  css  js  c++  java
  • 每日一题leetcode

    剑指 Offer 40. 最小的k个数

    输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8这8个数字,则最小的4个数字是1、2、3、4。

    示例 1:

    输入:arr = [3,2,1], k = 2
    输出:[1,2] 或者 [2,1]
    示例 2:

    输入:arr = [0,1,2,1], k = 1
    输出:[0]

    快速排序原理:
    快速排序算法有两个核心点,分别为 “哨兵划分” 和 “递归” 。

    哨兵划分操作: 以数组某个元素(一般选取首元素)为 基准数 ,将所有小于基准数的元素移动至其左边,大于基准数的元素移动至其右边

    class Solution {
        public int[] getLeastNumbers(int[] arr, int k) {
            int l = 0;
            int h = arr.length -1;
            quickSort(arr, l, h);
            return Arrays.copyOf(arr,k);
    
        }
        public void quickSort(int[]arr, int low, int hight){
            if(low >= hight)
                return;
            int i = low,j = hight; 
            while(i < j){
                while(i < j && arr[j] >= arr[low])j--;
                while(i < j && arr[i] <= arr[low])i++;
                
                swap(arr,i,j);
            }
            swap(arr,i,low);
            //递归哨兵划分
            quickSort(arr, low,i-1);
            quickSort(arr, i+1,hight);
        }
        public void swap(int[]arr, int i, int j){
            int temp = 0;
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    

      

  • 相关阅读:
    Mac + Python3 安装scrapy
    Pyqt4+Eric6+python2.7.13(windows)
    js基础⑥
    python模块之os,sys
    Python模块之random
    Python模块之PIL
    js基础⑤
    js基础④
    js基础③
    centOS目录结构详细版
  • 原文地址:https://www.cnblogs.com/nenu/p/15136840.html
Copyright © 2011-2022 走看看