-
Notifications
You must be signed in to change notification settings - Fork 0
/
Move_zeros.java
39 lines (39 loc) · 923 Bytes
/
Move_zeros.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
https://leetcode.com/problems/move-zeroes/
class Solution {
public void moveZeroes(int[] nums) {
int i = 0;
for(int j = 0 ; j < nums.length ; j++){
if(nums[j] != 0) {
nums[i] = nums[j];
i++;
}
}
for(int k = i ; k < nums.length; k++){
nums[k] = 0;
}
}
}
approach 2;
class Solution {
public void moveZeroes(int[] nums) {
if(nums.length<2){
return;
}
int left = 0;
int right = 1;
while(right < nums.length){
if(nums[left] != 0){
left ++;
right ++;
}
else if(nums[right] == 0){
right ++ ;
}
else{
int temp = nums[right];
nums[right] = nums[left];
nums[left] = temp ;
}
}
}
}