寻找一种算法,该算法将删除在数组的开头和结尾处出现的null,并且中间没有O(n)

例如:

[null, null, 1, 2, 3, null, null, null] -> [1, 2, 3]

[null, null, 1, 2, null, 3, null, null, null] -> [1, 2, null, 3]

[1, null, 2, 3, null, 4, null, null, null] -> [1, null, 2, 3, null, 4]

[null, null, 2, 3, null, 4, null, null, 5] -> [2, 3, null, 4, null, null, 5]

最佳答案

有点矮胖但是可以用。



const tests = [[null, null, 1, 2, 3, null, null, null],
[null, null, 1, 2, null, 3, null, null, null],
[1, null, 2, 3, null, 4, null, null, null],
[null, null, 2, 3, null, 4, null, null, 5]];

const strip = (arr) => {
  const end = arr.length-(arr.reverse().findIndex(a => a != null));
  const start = arr.reverse().findIndex(a => a != null);
  return arr.slice(start, end);
};

tests.forEach(a => console.log(strip(a)));





一个循环,检查开始和结束。



const tests = [[null, null, 1, 2, 3, null, null, null],
[null, null, 1, 2, null, 3, null, null, null],
[1, null, 2, 3, null, 4, null, null, null],
[null, null, 2, 3, null, 4, null, null, 5],
[null, null, null, null, null],
[null, 1, null, null, null, null]
];

const strip = (arr) => {
  let start = -1, end = -1, i = 0, x = arr.length - 1;
  while(start === -1 || end === -1) {
    if(start === -1 && arr[i] !== null) {
        start = i;
    }
    if(end === -1 && arr[x] !== null) {
        end = x+1;
    }
    if(i === x) return [];
    x--;
    i++;
  }
  return arr.slice(start, end);
};




tests.forEach(a => console.log(strip(a)));





好的,这是一个超级简单的解决方案。



const tests = [[null, null, 1, 2, 3, null, null, null],
[null, null, 1, 2, null, 3, null, null, null],
[1, null, 2, 3, null, 4, null, null, null],
[null, null, 2, 3, null, 4, null, null, 5],
[null, null, null, null, null]
];

const strip = (arr) => {
  while(arr[0] === null && arr.length > 0) {
    arr.shift();
  }
  while(arr[arr.length-1] === null && arr.length > 0) {
    arr.pop();
  }
  return arr;
};

tests.forEach(a => console.log(strip(a)));

10-08 14:43