我正在尝试解决leetcode问题:
给定一个数组num,编写一个函数将所有0移到其末尾,同时保持非零元素的相对顺序。示例:输入:[0,1,0,3,12]输出:[1,3,12,0,0]
而且我认为我有正确的解决方案,但是我不确定为什么我将其弄错了。
class Solution {
public void moveZeroes(int[] nums) {
for (int i = 0; i > nums.length;i++) {
int j= i;
while ((j<nums.length) && (nums[j]==0)){
j++;
}
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}
}
}}您可以使用一个指针解决此问题O(N)。这将通过:
public class Solution {
public static void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0)
return;
int pos = 0;
for (int num : nums)
if (num != 0)
nums[pos++] = num;
while (pos < nums.length)
nums[pos++] = 0;
}}for循环是不正确的(必须是i < nums.length),此外,如果无事可做,您的解决方案将无法正常工作:
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));产生于:
org.junit.ComparisonFailure: expected:<[[1, 2], 0, 0]> but was:<[[0, 0], 0, 0]>
自己编写一些测试用例,看看有什么问题。
在您的情况下:
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}是错误的,因为您正在i与交换j,即使i == j和nums[i] != 0。
由于我认为您不是在寻求可行的解决方案,因此我不会提供解决方案。但是这是我的测试用例:
@Testpublic void testEmptyArray() {
int[] array = new int[0];
moveZeroes(array);
assertEquals(0,array.length);}@Testpublic void testZeroOnlyArrays() {
int[] array = {0,0,0,0};
final String arrayString = Arrays.toString(array);
moveZeroes(array);
assertEquals(arrayString, Arrays.toString(array));;}@Testpublic void mixedTest() {
int[] array = {0,1,0,2};
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
moveZeroes(array);
assertEquals(expectedString, Arrays.toString(array));;
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));}“ for”循环应为:for (int i = 0; i < nums.length;i++) 然后,您的循环将从0开始在数组索引上运行,直到达到数组的长度。
当您定义i = 0时,当前代码甚至都不会进入循环,并且仅当循环条件大于数组大小时才运行循环条件:(i> nums.length)当然不正确
您正在使用i > nums.length这就是为什么不执行循环的原因
您需要一个非零值的索引。在我的解决方案j中,这里是针对非零值索引的意思是当您找到非零值集j索引并对其进行递增时。
public void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[j] = nums[i];
j++;
}
if (j < i) {
nums[i] = 0;
}
}
}