Find the nth smallest value


Posted by Christy on 2022-04-23

Description: Write a function named findNthMin that accepts an array and a number n. Find the nth smallest value

Note: Don’t use built-in function sort() and the numbers in the array will not repeat.

Answer 1:

Find minimum value first and delete the minimum value and find minimum value again.

If I would like to find the second smallest value, I will delete the value once, which means it needs to delete the value n - 1 times.

function findMin(arr) {
  let min = arr[0];
  let minIndex = 0;
  for (let i = 1; i < arr.length; i++) {
    if (min > arr[i]) {
      min = arr[i];
      minIndex = i;
    }
  }
  return minIndex;
}

function findNthMin(arr, nth) {
  for (let i = 1; i <= nth - 1; i++) {
    let minIndex = findMin(arr);
    arr.splice(minIndex, 1);
  }
  let realMinIndex = findMin(arr);
  return arr[realMinIndex];
}
console.log(findNthMin([1, 2, 3], 2));

Answer 2:

function findMin(arr) {
  let min = arr[0];
  let minIndex = 0;
  for (let i = 1; i < arr.length; i++) {
    if (min > arr[i]) {
      min = arr[i];
      minIndex = i;
    }
  }
  return minIndex;
}

function findNthMin(arr, nth) {
  for (let i = 1; i <= nth - 1; i++) {
    let minIndex = findMin(arr);
    arr = arr.filter((item, index) => {
      return index !== minIndex;
    });
  }
  let realMinIndex = findMin(arr);
  return arr[realMinIndex];
}
console.log(findNthMin([1, 2, 3], 2));









Related Posts

Day07 - 網格排版

Day07 - 網格排版

鏈結串列(Linked List)& 陣列(Array)

鏈結串列(Linked List)& 陣列(Array)

TypeScript

TypeScript


Comments