OFFER ---- 40-2 wins the largest number of K (the number of variants of the smallest K) (js achieve)

topic

Input n integers, find out the maximum number K. 4,5,1,6,2,7,3,8 e.g. eight digital input, then the maximum is four numbers 8,7,6,5.

Interview often ask: n takes a large number from the inside before the number 1000000, or n-th largest number taken from the inside number 1000000


Thinking

The minimum number of K seek to build on top of a small heap, seeking the largest number of K to build a large pile top, then continue to take the top of the heap element, and then re-built reactor


// 取前n大的数
function GetMaxestNumbers_Solution(input, k) {
  // write code here
  var startIndex = Math.floor(input.length / 2) - 1;
  var result = []
  for (var i = startIndex; i >= 0; i--) {
    heapAdjust(input, i, input.length)
  }
  for (var j = input.length - 1; j > input.length - 1 - k; j--) {
    result.push(input[0])
    swap(input, 0, j)
    heapAdjust(input, 0, j)
  }
  return result
}

function heapAdjust(arr, s, m) {
  var temp = arr[s]
  for (var i = s * 2 + 1; i < m; i = i * 2 + 1) {
    if ((i + 1) < m && arr[i + 1] > arr[i]) {
      i++
    }
    if (temp > arr[i]) {
      break
    } else {
      arr[s] = arr[i]
      s = i
    }
    arr[s] = temp
  }
}

function swap(arr, i, j) {
  var temp = arr[i]
  arr[i] = arr[j]
  arr[j] = temp
}
// 取第n大的数
function GetLeastNumbers_Solution(input, k) {
  // write code here
  var startIndex = Math.floor(input.length / 2) - 1;
  for (var i = startIndex; i >= 0; i--) {
    heapAdjust(input, i, input.length)
  }
  for (var j = input.length - 1; j > input.length - k; j--) {
    swap(input, 0, j)
    heapAdjust(input, 0, j)
  }
  return input[0]
}

function heapAdjust(arr, s, m) {
  var temp = arr[s]
  for (var i = s * 2 + 1; i < m; i = i * 2 + 1) {
    if ((i + 1) < m && arr[i + 1] > arr[i]) {
      i++
    }
    if (temp > arr[i]) {
      break
    } else {
      arr[s] = arr[i]
      s = i
    }
    arr[s] = temp
  }
}

function swap(arr, i, j) {
  var temp = arr[i]
  arr[i] = arr[j]
  arr[j] = temp
}

Guess you like

Origin blog.csdn.net/qq_40816360/article/details/94654872