leetcode.com/problems/move-zeroes/
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.
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
class Solution {
public void moveZeroes(int[] nums) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[index] = nums[i];
index++;
}
}
while (index < nums.length) {
nums[index] = 0;
index++;
}
}
}
'개발자 > algorithm' 카테고리의 다른 글
LeetCode, Best Time to Buy and Sell Stock (Java) (0) | 2021.01.05 |
---|---|
LeetCode, Single Number (Java) (0) | 2021.01.05 |
LeetCode, Invert Binary Tree (Java) (0) | 2021.01.03 |
LeetCode, Maximum Depth of Binary Tree (Java) (0) | 2021.01.03 |
LeetCode, Merge Two Binary Trees (Java) (0) | 2021.01.03 |