728x90
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.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
class Solution {
public void moveZeroes(int[] nums) {
int i, idx = 0;
for( i = 0; i < nums.length; i++ )
if( nums[i] != 0 )
nums[idx++] = nums[i];
for( i = idx; i < nums.length; i++ )
nums[i] = 0;
}
}
반응형
'코딩 문제 풀기 ( Algorithm problem solving ) > 릿코드 ( LeetCode )' 카테고리의 다른 글
[LeetCode] (#844) Backspace String Compare (0) | 2020.04.26 |
---|---|
[LeetCode] (#876) Middle of the Linked List (0) | 2020.04.26 |
[LeetCode] (#) Counting Elements (0) | 2020.04.26 |
[LeetCode] (#202) Happy Number (0) | 2020.04.26 |
[LeetCode] (#136) Single Number (0) | 2020.04.26 |