4 Nisan 2020 Cumartesi

Dizideki Sıfırları Sona Taşıma




>> Solution 1:


--
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;
}
}
view raw MoveZeroes.java hosted with ❤ by GitHub
--






>> Solution 2 :


--
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: