Total Accepted: 87958
Total Submissions: 196336
Difficulty: Easy
Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function,
nums should be [1, 3, 12, 0, 0].
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
最开始的想法是针对数组中为0的数字进行操作,即遇到一个为0的数字就将其
放在数组最后面。但是这样会使得数字的循环数i定义变得模糊,
循环一直在进行,没办法停止。所以转换思路,针对数组中为1的数字进行操作。
方法一:插入
public class Solution {
public void moveZeroes(int[] nums) {
int temp = 0;
for(int i = 0; i < nums.length; i ++) {
if(nums[i] != 0) {
nums[temp] = nums[i];
temp ++;
}
}
if(temp < nums.length) {
for(int i = temp; i < nums.length; i ++) {
nums[i] = 0;
}
}
}
}将数组为1的数字依次放在数字的第1,2,3位,需要一个标记数temp代表此数。
方法2:交换
public class Solution {
public void moveZeroes(int[] nums) {
int temp = 0;
for(int i = 0; i < nums.length; i++) {
if( nums[i] != 0) {
int m = nums[i];
nums[i] = nums[temp];
nums[temp] = m;
temp ++;
}
}
}
}这里是将为1的数字与数组第1,2,3位数字进行交换。
在这里,强调一下java中foreach循环与for循环的差别,第一次我将该代码用
另一种方式进行书写,即foreach方法。
public class Solution {
public void moveZeroes(int[] nums) {
int temp = 0;
for(int c:nums) {
if( c!= 0) {
int m = c;
c = nums[temp];
nums[temp] = m;
temp ++;
}
}
}
}该方法只是循环方法不同而已(方法2的一个变形),但是答案却不是
正确答案。在这里强调一下java中for与foreach的区别?
1.如果只是遍历集合或者数组,用foreach好些,快些。
2. 如果对集合中的值进行修改,就要用for循环了。其实foreach的内部原理
2. 如果对集合中的值进行修改,就要用for循环了。其实foreach的内部原理
其实也是Iterator,但它不能像Iterator一样可以人为的控制,而且也不能调用
iterator.remove();更不能使用下标来访问每个元素,所以不能用于增加,删
除等复杂的操作。举个例子:
for(String aid:list){
<span style="white-space:pre"> </span>if(aid.equals("aa")){
<span style="white-space:pre"> </span>list.remove(aid); //这行会报错,不能修改list的长度
<span style="white-space:pre"> </span>}
}
所以foreach语句是for语句的特殊简化版本,但是foreach语句并不能完全取代
for语句。
本文详细介绍了如何通过两种方法(插入和交换)在不复制数组的情况下,将数组中的所有0元素移至数组末尾,同时保持非零元素的相对顺序。并对比了Java中foreach循环与for循环的区别,解释了为什么在特定场景下使用foreach循环可能导致错误。

41万+

被折叠的 条评论
为什么被折叠?



