zoukankan      html  css  js  c++  java
  • leetcode面试题 17.14. 最小K个数(快速排序,只排序一边)

    package com.andy.springtransaction.aglorithm;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    //面试题 17.14. 最小K个数
    class Solution {
        public static void main(String[] args) {
    
            int [] arr={1,3,5,7,2,4,6,1,8};
            int k=4;
            int[] ints = new Solution().smallestK(arr, k);
            Arrays.stream(ints).forEach(System.out::println);
        }
        public int[] smallestK(int[] arr, int k) {
            int[] result=new int[k];
            if(arr==null||arr.length==0){
                return result;
            }
            if(k<=0||k>=arr.length){
                return result;
            }
            quickSort(arr,0,arr.length-1,k);
    
    
            for(int i=0;i<k;i++){
                result[i]=arr[i];
            }
            return result;
    
        }
    
        public void quickSort(int[] arr,int originStart,int originEnd,int k){
            int start=originStart;
            int end=originEnd;
            int temp=arr[originStart];
            if(start>=end){
                return;
            }
    
            while(start<end){
                while(start<end&&temp<=arr[end]){
                    end--;
                }
                if(start<end){
                    arr[start]=arr[end];
                }
                while(start<end&&temp>=arr[start]){
                    start++;
                }
                if(start<end){
                    arr[end]=arr[start];
                }
            }
            arr[start]=temp;
            if(start==k){
                return;
            }else if(start>k){
                quickSort(arr,originStart,start-1,k);
            }else{
                quickSort(arr,start+1,originEnd,k);
            }
        }
    }
  • 相关阅读:
    PAT 乙级 1041 考试座位号(15) C++版
    四、Shell输入、输出功能和字符颜色设置
    三、Shell变量类型和运算符
    Shell文件权限和脚本执行
    Spark Standalone
    Loadrunner安装
    kali 2.0源更新
    xmanager远程桌面连接Linux
    Linux--文件查找命令
    Linux下MySQL忘记密码
  • 原文地址:https://www.cnblogs.com/mkl34367803/p/14697628.html
Copyright © 2011-2022 走看看