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

[BE201] 後端中階:ORM 與 Sequelize

[BE201] 後端中階:ORM 與 Sequelize

[FE302] React 基礎 - hooks 版本:React 實戰篇 - 留言板

[FE302] React 基礎 - hooks 版本:React 實戰篇 - 留言板

python-helloWorld

python-helloWorld


Comments