>> Solution 1:
--
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.stream.Collectors; | |
public class MoveZeroes { | |
public static void main(String[] args) { | |
MoveZeroes problem = new MoveZeroes(); | |
int[] result1 = problem.calculate(new int[] { 0, 1, 0, 3, 12 }); | |
System.out.println( | |
"Expected: [1,3,12,0,0], " + "Result: " + Arrays.stream(result1).boxed().collect(Collectors.toList())); | |
} | |
/** | |
* 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. | |
* | |
* @param nums | |
* @return | |
*/ | |
public int[] calculate(final int[] nums) { | |
int[] result = Arrays.copyOf(nums, nums.length); | |
int countZero = 0; | |
boolean moveNums = false; | |
for (int i = 0; i < result.length; i++) { | |
if (result[i] == 0) { | |
countZero++; | |
moveNums = true; | |
} else if (moveNums) { | |
result[i - countZero] = result[i]; | |
} | |
} | |
while (countZero > 0) { | |
result[result.length - countZero] = 0; | |
countZero--; | |
} | |
return result; | |
} | |
} |
>> Solution 2 :
--
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.stream.Collectors; | |
public class MoveZeroesOptimal { | |
public static void main(String[] args) { | |
MoveZeroesOptimal problem = new MoveZeroesOptimal(); | |
int[] result1 = problem.calculate(new int[] { 0, 1, 0, 3, 12 }); | |
System.out.println( | |
"Expected: [1,3,12,0,0], " + "Result: " + Arrays.stream(result1).boxed().collect(Collectors.toList())); | |
} | |
/** | |
* 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. | |
* | |
* @param nums | |
* @return | |
*/ | |
public int[] calculate(final int[] nums) { | |
int[] result = Arrays.copyOf(nums, nums.length); | |
int countZero = 0; | |
boolean moveNums = false; | |
for (int i = 0; i < result.length; i++) { | |
if (result[i] == 0) { | |
countZero++; | |
moveNums = true; | |
} else if (moveNums) { | |
result[i - countZero] = result[i]; | |
result[i] = 0; | |
} | |
} | |
return result; | |
} | |
} |
Hiç yorum yok:
Yorum Gönder