Skip to content

Commit e9cceed

Browse files
move zeroes
1 parent 3b62ab0 commit e9cceed

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

‎EASY/src/easy/MoveZeroes.java

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package easy;
2+
3+
import utils.CommonUtils;
4+
5+
/**283. Move Zeroes QuestionEditorial Solution My Submissions
6+
Total Accepted: 105705
7+
Total Submissions: 231420
8+
Difficulty: Easy
9+
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.
10+
11+
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
12+
13+
Note:
14+
You must do this in-place without making a copy of the array.
15+
Minimize the total number of operations.*/
16+
public class MoveZeroes {
17+
public void moveZeroes_Editorial_solution2(int[] nums){
18+
//this solutoin is the most optimal since it minimizes the number of operations
19+
//the idea is to swap the non-zero element to the first zero number position
20+
for(int i = 0, j = 0; i < nums.length && j < nums.length; i++){
21+
if(nums[i] != 0){
22+
int temp = nums[i];
23+
nums[i] = nums[j];
24+
nums[j] = temp;
25+
j++;
26+
}
27+
}
28+
}
29+
30+
public void moveZeroes_Editorial_solution1(int[] nums){
31+
//keep the last non-zero index and keep overwriting it, then append zeroes to fill the end
32+
int j = 0, i = 0;
33+
for(; j < nums.length; j++){
34+
if(nums[j] != 0){
35+
nums[i++] = nums[j];
36+
}
37+
}
38+
for(; i < nums.length; i++){
39+
nums[i] = 0;
40+
}
41+
}
42+
43+
//then I came up with this solution and got it AC'ed! Cheers!
44+
//basically, find the next non-zero number and swap it with the current zero number
45+
//Apparently it's not the most optimal, since this is basically an O(n^2) solution, then I turned to Editorial solutions
46+
public void moveZeroes(int[] nums){
47+
for(int i = 0; i < nums.length-1; i++){
48+
if(nums[i] == 0){
49+
int j = i+1;
50+
while(j < nums.length && nums[j] == 0){
51+
j++;
52+
}
53+
if(j >= nums.length) return;
54+
else {
55+
int temp = nums[j];
56+
nums[j] = nums[i];
57+
nums[i] = temp;
58+
}
59+
}
60+
}
61+
}
62+
63+
//this approach won't preserve the relative order of the non-zero numbers
64+
public void moveZeroes_1st_attempt(int[] nums) {
65+
int i = 0, j = nums.length-1;
66+
while(i < j){
67+
if(nums[i] == 0){
68+
int temp = nums[j];
69+
nums[j] = nums[i];
70+
nums[i] = temp;
71+
j--;
72+
} else {
73+
i++;
74+
}
75+
}
76+
CommonUtils.printArray(nums);
77+
}
78+
79+
public static void main(String...strings){
80+
MoveZeroes test = new MoveZeroes();
81+
int[] nums = new int[]{0,1,0,3,12};
82+
test.moveZeroes_Editorial_solution2(nums);
83+
}
84+
}

0 commit comments

Comments
 (0)