Leetcode 283) Move Zeroes
in Algorithms
- The new position for zero was a bit unclear. but now it is clear! BUT, next zero position will be curzero+1 ! since we are going from left to right, there would be two cases 1. 000231 (0 is next to 0) 2. 0223400 (0 is not next to 0) => in this case, we swap with non zero value. and that is right next to !!!!
class Solution {
public void moveZeroes(int[] nums) {
int posZero=0;
for(int i =0;i<nums.length;i++){
/*
if nums[i]==0 =>posZero won't be updated. because, it should hold the first 0 value of the array.
we process from the beginning
*/
if(nums[i]!=0){
//since we processed all 0 in front of
swap(posZero,i,nums);
posZero++;
}
}
/*
Since we can simply override, the elemnts!!! I don't have to use while loop to implement the algorithm
for(int i=0;i<nums.length;i++){
if(nums[i]==0){
int ptr = i;
while(ptr<nums.length && nums[ptr]==0){
ptr++;
}
if(ptr<nums.length)swap(i,ptr,nums);
}
}*/
}
public void swap(int i ,int j , int[] nums){
int tmp = nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
}
다른 풀이
- 등장한 0의 개수를 센 후에, index-등장한 0의 개수 를 해서 값을 저장해준다!
class Solution {
public void moveZeroes(int[] nums) {
int numZeros = 0;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 0) {
numZeros++;
} else {
int temp = nums[i];
nums[i] = 0;
//zero나온 만큼 인덱스가 앞으로 가니까..
nums[i - numZeros] = temp;
}
}
}
}