Algorithm interview questions

1. deduplication array

There is an array [7, 8, 3, 5, 1, 2, 4, 3, 1], a method to write a diff "deduplication" and "descending output" and "currency format." Expected result: "8,754,321"

 

const arr = [ 7, 8, 3, 5, 1, 2, 4, 3, 1 ];
let unique = [...new Set(arr)].sort((a,b) => a-b)
let a = unique.map((item,index) => {
if (index % 3 === 0 && index !==0) {
return item + ','
}
return item
}).reverse().join('')
console.log(a);

2. Asynchronous serial loading

There is an array: const imgs = [ 'url1', 'url2', 'url3', ...];

Please realize the effect of:

//1)回调函数实现
function loadImage(imgs) {
  const img = new Image();
  const url = imgs.shift();
  if (url) {
    img.src = url;
    img.onload = function() {
      if (imgs.length > 0)
      loadImage(imgs)
    }
  } 
}
// 2)async await-promise实现
function loadImage(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = url;
    img.onload = function() {
      resolve()
    }
  })
}
async function loadImages() {
  for(let url of imgs) {
    await loadImage(url);
  } 
}

3. array traversal

Loading the queues in accordance with image array image (Note: After loading a next reload)
Write an efficient algorithm to complete the search matrix, the matrix has the following characteristics:
1) each row of numbers in the matrix are sorted, and increases from left to right.
2) the last digit of the first number of each line on the line than big

// E.g:

let arr = [
  [2, 4, 8, 9],
  [10, 13, 15, 21],
  [23, 31, 33, 51]
]
function findValue(num) {
  const maxOfArr = arr.map(item => item[item.length - 1]);
  let innerIndex = 0;
  for(let i of maxOfArr) {
    console.log(i)
    if (num <= i) {
      innerIndex = maxOfArr.indexOf(i);
      break;
    }
  }
  return !!(arr[innerIndex].find(item => item === num))
}
console.log(findValue(21));

 

 

Guess you like

Origin www.cnblogs.com/lyraLee/p/12077127.html