找不到数组反转算法问题的解决方案。

huangapple go评论78阅读模式
英文:

Can't find a solution for array reverse algorithm problem

问题

I have a requirement where I have to reverse an array without changing the index of '#' presents in an array, like below example:

  • Array [18,-4,'#',0,8,'#',5] should return [5, 8, "#", 0, -4, "#", 18], here numbers should be reversed, excluding '#' while keeping the same index.

I have tried to get the correct output, but it doesn't seem to be correct in all scenarios:

var arr = [18,-4,'#',0,8,'#',5]; // giving result is correct
var arr1 = [18,-4,0,'#',8,'#',5]; // result is not correct
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));
英文:

I have a requirement where I have to reverse an array without changing the index of '#' presents in an array, like below example:

  • Array [18,-4,&#39;#&#39;,0,8,&#39;#&#39;,5] should return [5, 8, &quot;#&quot;, 0, -4, &quot;#&quot;, 18], here numbers should be reversed, excluding '#' while keeping the same index.

I have tried to get the correct output, but it doesn't seem to be correct in all scenarios:
var arr = [18,-4,'#',0,8,'#',5]; // giving result is correct
var arr1 = [18,-4,0,'#',8,'#',5]; // result is not correct

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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&lt;parseInt(numbers.length/2);i++) {
  	if(numbers[i] === &#39;#&#39;) {
    	start = i+1;
      end = numbers.length - i - i;
      reverse(numbers, start, end);
    } else if (numbers[numbers.length - i - 1] === &#39;#&#39;) {
    	start = i;
      end = numbers.length - i - 2;
      reverse(numbers, start, end);
    } else {
    	reverse(numbers, start, end);
    }
  }
  return numbers;
}

var arr = [18,-4,&#39;#&#39;,0,8,&#39;#&#39;,5];
var arr1 = [18,-4,0,&#39;#&#39;,8,&#39;#&#39;,5];
console.log(flip(arr));
console.log(flip(arr1));

<!-- end snippet -->

答案1

得分: 2

你可以简化这个函数,只使用两个索引,起始和结束,检查索引处的值是否应该保持不变,然后选择另一个索引进行交换。

const
    swap = (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;
            }
            swap(numbers, start++, end--);
        }
        return numbers;
    },
    array1 = [18, -4, '#', 0, 8, '#', 5],
    array2 = [18, -4, 0, '#', 8, '#', 5];

console.log(...flip(array1));
console.log(...flip(array2));

注意:我保留了代码中的特殊字符和标记,如#,没有进行翻译。

英文:

You could simplify the function and use only two indices, the start and end and check if the value at the indices should stay, then choose another index for swapping.

<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
swap = (array, a, b) => [array[a], array[b]] = [array[b], array[a]],
flip = numbers => {
var start = 0,
end = numbers.length - 1;

        while (start &lt; end) {
            if (numbers[start] === &#39;#&#39;) {
                start++;
                continue;
            }
            if (numbers[end] === &#39;#&#39;) {
                end--;
                continue;
            }
            swap(numbers, start++, end--);
        }
        return numbers;
    },
    array1 = [18, -4, &#39;#&#39;, 0, 8, &#39;#&#39;, 5],
    array2 = [18, -4, 0, &#39;#&#39;, 8, &#39;#&#39;, 5];

console.log(...flip(array1));
console.log(...flip(array2));

<!-- end snippet -->

答案2

得分: 2

以下是翻译好的部分:

"The trivial approach would be to remove all &#39;#&#39;'s, reverse the array using the built-in [].reverse method, and then re-insert the &#39;#&#39;'s:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let flip = numbers =&gt; {
  let removed = numbers.reduce((r, v, i) =&gt;
          v === &#39;#&#39; ? r.concat(i) : r
      , []);

  let reversed = numbers.filter(v =&gt; v !== &#39;#&#39;).reverse();

  removed.forEach(i =&gt; reversed.splice(i, 0, &#39;#&#39;));

  return reversed;
};

let arr = [18, -4, &#39;#&#39;, 0, 8, &#39;#&#39;, 5];
let arr1 = [18, -4, 0, &#39;#&#39;, 8, &#39;#&#39;, 5];
console.log(flip(arr));
console.log(flip(arr1));

<!-- end snippet -->"

请注意,我已经忽略了代码部分,只翻译了您提供的文字。

英文:

The trivial approach would be to remove all &#39;#&#39;'s, reverse the array using the built in [].reverse method, and then re-insert the &#39;#&#39;'s:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let flip = numbers =&gt; {
  let removed = numbers.reduce((r, v, i) =&gt;
          v === &#39;#&#39; ? r.concat(i) : r
      , []);

  let reversed = numbers.filter(v =&gt; v !== &#39;#&#39;).reverse();

  removed.forEach(i =&gt; reversed.splice(i, 0, &#39;#&#39;));

  return reversed;
};

let arr = [18, -4, &#39;#&#39;, 0, 8, &#39;#&#39;, 5];
let arr1 = [18, -4, 0, &#39;#&#39;, 8, &#39;#&#39;, 5];
console.log(flip(arr));
console.log(flip(arr1));

<!-- end snippet -->

答案3

得分: 1

你可以尝试这样做:

var numbers = arr.filter(a => a !== '#')
var revArr = [];
arr.forEach((currentValue) => {
    if(currentValue !== "#") {
        revArr.push(numbers.pop());
    } else {
        revArr.push("#");
    }
});
英文:

You can try this:

var numbers = arr.filter(a =&gt; a !== &#39;#&#39;)
var revArr = [];
arr.forEach((currentValue) =&gt; {
    if(currentValue !== &quot;#&quot;) {
        revArr.push(numbers.pop());
    } else {
        revArr.push(&quot;#&quot;);
    }
});

答案4

得分: 1

你可以基于两个基本数组来设计你的算法(一个是包含反转数字的数组,另一个是包含保存位置的"#"的数组)。

const array = [5, 8, "#", 0, -4, "#", 18];

function flip(array) {
  const arrayNumbers = array.filter((el, index) => el !== "#").reverse();
  var counter = 0;
  return array.map(el => el === "#").map(el => {
    if (!el) {
      let num = arrayNumbers[counter];
      counter = counter + 1;
      return num;
    } else {
      return "#";
    }
  })
}

console.log(flip(array));

希望这有帮助。

英文:

You can base your algorithm on two basic array (array of reversed numbers and and an array with "#" saved positions)

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const array = [5, 8, &quot;#&quot;, 0, -4, &quot;#&quot;, 18];

function flip(array) {

  const arrayNumbers = array.filter((el, index) =&gt; el !== &quot;#&quot;).reverse();

  var counter = 0;

  return array.map(el =&gt; el === &quot;#&quot;).map(el =&gt; {
    if (!el) {
      let num = arrayNumbers
0
+
网站访问量
; counter = counter + 1; return num; } else { return &quot;#&quot; } }) } console.log(flip(array));

<!-- end snippet -->

答案5

得分: 0

Here's the translated code portion:

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);

Please note that the code has been translated, and I've excluded the additional explanations and comments.

英文:
var arr = [18,-4,&#39;#&#39;,0,8,&#39;#&#39;,5]
var stack = []

for (i=0 ; i&lt;arr.length; i++) {
	if (arr[i] == &#39;#&#39;) continue;
	stack.push(arr[i]);
}

for (i=0 ; i&lt;arr.length; i++) {
	if (arr[i] != &#39;#&#39;) {
		arr[i] = stack.pop();
	}
}

console.log(arr)

The above code should solve your problem.
<br>
The implementation uses stack where we keep inserting elements into stack untill we see a '#' and skip it.
While creating the output array we refer the original array for '#' index and stack for reverse index.

答案6

得分: 0

这部分的代码可以这样做:

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));
英文:

You can do it like this.

		int end = v.length - 1;
		int start = 0;
		for (int i = 0; i &lt; v.length &gt;&gt; 1; i++) {
			if (v[start].equals(&quot;#&quot;)) {
				start++;
				continue;
			}
			if (v[end].equals(&quot;#&quot;)) {
				end--;
				continue;
			}
			Object temp = v[end];
			v[end] = v[start];
			v[start] = temp;
			end--;
			start++;

		}
		System.out.println(Arrays.toString(v));

</details>



huangapple
  • 本文由 发表于 2020年1月6日 22:55:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定