我有一个必须在不更改数组中存在的'#'索引的情况下反转数组的要求,例如以下示例:
[18,-4,'#',0,8,'#',5]
应该返回[5, 8, "#", 0, -4, "#", 18]
,这里的数字应该颠倒,但在保持相同索引的情况下不包括'#'。我已经尝试获得正确的输出,但是似乎并非在所有情况下都是正确的:var arr = [18,-4,'#',0,8,'#',5]; //给出正确的结果var arr1 = [18,-4,0,'#',8,'#',5]; //结果不正确
var reverse = function(numbers, start, end){
var temp = numbers[start];
numbers[start] = numbers[end];
numbers[end] = temp;
}
var flip = function(numbers) {
var start = 0;
var end = numbers.length-1;
for(var i=0;i<parseInt(numbers.length/2);i++) {
if(numbers[i] === '#') {
start = i+1;
end = numbers.length - i - i;
reverse(numbers, start, end);
} else if (numbers[numbers.length - i - 1] === '#') {
start = i;
end = numbers.length - i - 2;
reverse(numbers, start, end);
} else {
reverse(numbers, start, end);
}
}
return numbers;
}
var arr = [18,-4,'#',0,8,'#',5];
var arr1 = [18,-4,0,'#',8,'#',5];
console.log(flip(arr));
console.log(flip(arr1));
var arr = [18,-4,'#',0,8,'#',5]
var stack = []
for (i=0 ; i<arr.length; i++) {
if (arr[i] == '#') continue;
stack.push(arr[i]);
}
for (i=0 ; i<arr.length; i++) {
if (arr[i] != '#') {
arr[i] = stack.pop();
}
}
console.log(arr)
上面的代码应该可以解决您的问题。该实现使用堆栈,在该堆栈中,我们一直将元素插入堆栈,直到看到“#”并跳过它。在创建输出数组时,我们将原始数组引用为“#”索引,将堆栈引用为反向索引。
您可以简化功能,仅使用两个索引,即开始和结束,并检查索引处的值是否应保留,然后选择另一个索引进行交换。
const
reverse = (array, a, b) => [array[a], array[b]] = [array[b], array[a]],
flip = numbers => {
var start = 0,
end = numbers.length - 1;
while (start < end) {
if (numbers[start] === '#') {
start++;
continue;
}
if (numbers[end] === '#') {
end--;
continue;
}
reverse(numbers, start++, end--);
}
return numbers;
}
var arr = [18, -4, '#', 0, 8, '#', 5];
var arr1 = [18, -4, 0, '#', 8, '#', 5];
console.log(...flip(arr));
console.log(...flip(arr1));
您可以尝试以下方法:
var numbers = arr.filter(a => a !== '#')
var revArr = [];
arr.forEach((currentValue) => {
if(currentValue !== "#") {
revArr.push(numbers.pop());
} else {
revArr.push("#");
}
});
您可以这样操作。
int end = v.length - 1;
int start = 0;
for (int i = 0; i < v.length >> 1; i++) {
if (v[start].equals("#")) {
start++;
continue;
}
if (v[end].equals("#")) {
end--;
continue;
}
Object temp = v[end];
v[end] = v[start];
v[start] = temp;
end--;
start++;
}
System.out.println(Arrays.toString(v));
简单的方法是删除所有'#'
,使用内置的[].reverse
方法反转数组,然后重新插入'#'
:
let flip = numbers => {
let removed = numbers.reduce((r, v, i) =>
v === '#' ? r.concat(i) : r
, []);
let reversed = numbers.filter(v => v !== '#').reverse();
removed.forEach(i => reversed.splice(i, 0, '#'));
return reversed;
};
let arr = [18, -4, '#', 0, 8, '#', 5];
let arr1 = [18, -4, 0, '#', 8, '#', 5];
console.log(flip(arr));
console.log(flip(arr1));