zoukankan      html  css  js  c++  java
  • 剑指offer 最小k个数

    设计一个算法,找出数组中最小的k个数。以任意顺序返回这k个数均可。

    示例:

    输入: arr = [1,3,5,7,2,4,6,8], k = 4
    输出: [1,2,3,4]
    提示:

    0 <= len(arr) <= 100000
    0 <= k <= min(100000, len(arr))

    /**
     * 快排
     * @param {number[]} arr
     * @param {number} k
     * @return {number[]}
     */
    var smallestK = function(arr, k) {
      if(k >= arr.length) return arr
      let low = 0
      let heigh = arr.length - 1
      while(low < heigh) {
          let pos = partiotion(arr, low, heigh)
          console.log(pos)
          if(pos === k - 1) {
              break
          }else if(pos < k-1) {
              low = pos + 1
          }else {
              heigh = pos - 1
          }
      }
      return arr.splice(0, k)
    };
    
    function partiotion (arr, low, heigh) {
    let pivot = arr[low]
    while(low < heigh) {
        while(low < heigh && arr[heigh] >= pivot) heigh --
        arr[low] = arr[heigh]
        while(low < heigh && arr[low] <= pivot) low ++
        arr[heigh] = arr[low]
    }
    arr[low] = pivot
    return low
    }
    
    // 冒泡排序
    function GetLeastNumbers_Solution(input, k)
    {
        // write code here
        const res = []
        if (input.length === 0) return res
        if (k > input.length) return res
        let temp
        for (let i = 0; i < k; i++) {
            for (let j = 0; j < input.length-i-1; j++) {
                if (input[j] < input[j+1]) {
                    temp = input[j+1]
                    input[j+1] = input[j]
                    input[j] = temp
                }
            }
            res.push(input[input.length-1-i])
        }
        return res
    }
  • 相关阅读:
    uva 562
    uva 624
    hdu 3826
    CF 89 div2 A
    看视屏学编程之接口、抽象类
    看视频学编程之SQL数据库基础
    看视频学编程之WinForm
    看视频学编程之骑士飞行棋—自己做(单机版)
    看视频学编程之继承
    看视频学编程之C#中的类
  • 原文地址:https://www.cnblogs.com/lyt0207/p/14039061.html
Copyright © 2011-2022 走看看