[Algorithm] Leetcode_Move Zeroes

JAsmine_log·2024년 3월 10일
0

Problem

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Example 2:
Input: nums = [0]
Output: [0]

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

Follow up:
Could you minimize the total number of operations done?

Analysis & Soulutions

  • nums[]의 사이즈가 고정되어 있다.
  • nums[]에서 요소가 0이 아니면 count를 세면서 차례대로 앞으로 보내주면된다, 그리고 전체-count만큼의 인덱스부터는 모두 0이다.

Code

class Solution {
    public void moveZeroes(int[] nums) {
        int[] array=new int[nums.length];
        int count=0;
        for (int i=0;i<nums.length;i++){
            if(nums[i]!=0){
                nums[count]=nums[i];
                count++;
            }            
        }
        for(int i=count;i<nums.length;i++){
            nums[i]=0;
        }
    }
}
profile
Everyday Research & Development

0개의 댓글