[Java] Leetcode 283. Move Zeroes [Two Pointers #2]

preview_player
Показать описание
In this video, I'm going to show you how to solve Leetcode 283. Move Zeroes which is related to Two Pointers.

In the end, you’ll have a really good understanding on how to solve Leetcode 283. Move Zeroes and questions that are similar to this Two Pointers.

Рекомендации по теме
Комментарии
Автор

Good solution, could be a little cleaner in terms of the if statements and that base case isn't required:
class Solution {
public void moveZeroes(int[] nums) {
int left = 0;
int right = 1;
while(right < nums.length){
if(nums[left] == 0){
if(nums[right] !=0){
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
else{
right++;
}
}
else{
left++;
right++;
}
}
}
}

anirudhakyathsandra
Автор

Great solution. The way you utilized the two pointers is very intuitive to follow.

DriveBreakFixRepeat
Автор

Probably don't need two pointer for this. Just loop through the array, move all the non-zeros to the front and then add zeros to to the remaining

shenth
Автор

Counting zeros is enough and we can use only one pointer to shift non zeros at the start of array:
time complexity -> O(N)
space complexity -> O(1)

class Solution {
public void moveZeroes(int[] nums) {
int left = 0;
int countOfZero = 0;

for (int i= 0; i < nums.length; i++) {
// counting zeros
if (nums[i] == 0) {
countOfZero ++;
continue;
}
// shift non-zeros to start of array
nums[left] = nums[i];
left ++;
}
// write zeros at the end of array
while ((left < nums.length) && (countOfZero > 0)) {
nums[left] = 0;
left ++;
countOfZero --;
}

}
}

afshinpaydar
Автор

class Solution {
public void moveZeroes(int[] nums) {
int L = 0, R = 0;
int N = nums.length;
while(R < N){
//1. anchor the L to a 0 element
if(nums[L] != 0){
L++;
R++; //L <= R
}
//2. explore the R to a non-zero element
else if(nums[R] == 0){
R++;
}
//3. swap L and R
else{
int temp = nums[R];
nums[R] = nums[L];
nums[L] = temp;
}
}
}
}

EricProgramming
Автор

For the else condition since Nums[L] is always zero, cant we just set nums[L] = 0, instead of nums[L] = temp

Rob-J-BJJ
Автор

muito bom, apesar de eu enteder pouco ingles.

samuelferreira
Автор

how it handles [1, 0] case Can anyone explain it to me?

vinoddiwan