如果为零,如何将数组中的元素向左移动1? [英] How do I shift elements in an array to the left by 1 if there is a zero?
问题描述
好,所以我必须遍历一个数组,如果数组中有零,那么我必须将零右边的元素向左移动1.
Ok so I have to go through an array and if there is a zero in the array then I have to shift the elements right of the zero to the left by 1.
例如,给定:
[3,0,1,2]
在调用该方法后,我应该得到:
after a call to the method I should get:
[3,1,2,0]
这是我到目前为止所拥有的;
This is what I have so far;
public int[] shiftArray(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] == 0) {
arr[i] = arr[i + 1];
}
arr[arr.length - 1] = 0;
}
return null;
}
我一直坚持如何将所有元素从零向右偏左移动1,而不只是从零向右偏右移动.
I'm stuck on how to shift all the elements right of zero to the left by 1 and not just the one right next to the zero.
推荐答案
您的算法/过程应重点关注的是:
The main thing your algorithm/procedure should focus on is this:
如果索引中的值为零且它不是最后一个索引,请执行两个操作:
If the value in an index is zero and it isn't the last index, perform two operations:
- 将索引的值移到右侧
- 将数字先前移至右侧的左侧.
以上步骤非常重要.我们发现您已经忽略了问题的第2步.
The steps above are very important. I see that you've neglected step 2 in your question.
这是我的处理方式:
public int[] shiftArray(int[] arr){
for(int i = 0; i < arr.length - 1; i ++) {
if((arr[i] == 0) && (i != (arr.length - 1))){
int prev = arr[i];
int next = arr[i + 1];
arr[i] = next;
arr[i + 1] = prev;
}
}
return arr;
}
我希望这会有所帮助..编码愉快!
I hope this helps.. Merry coding!
这篇关于如果为零,如何将数组中的元素向左移动1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!