Game Tech Blog

283. Move Zeroes 본문

Algorithm/LeetCode

283. Move Zeroes

jonghow 2023. 7. 25. 01:21
반응형

[문제]

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.

 

[TC]

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?

 

[접근]

TC 가 정렬된것 처럼 나열되어있길래, 선정렬 수행 후 0 찾아서 넣어서 리턴하려고 함.

그러나, 다른 TC에서 [2,1] 이 그대로 output 이 [2,1] 이길래 정렬을 과감히 버리고 submit 했더니 accept 나옴

투포인터 문제였는데 그냥 STL 로 풀음.

 

[코드] - C++

class Solution {
    public: vector<int> ret;
public:
    void moveZeroes(vector<int>& nums) {
        if(nums.size() ==1 ) return;

        int r = nums.size() -1;
        int l = 0;

        int zeroCnt = 0;

        for(int i = 0; i < nums.size(); ++i)
        {
            if(nums[i] == 0)
            {
                ++zeroCnt;
                continue;
            }

            ret.push_back(nums[i]);
        }

        for(int j = 0; j < zeroCnt; ++j)
            ret.push_back(0);

        nums = ret;
        return;
    }
};

[결과]

[시도]

[후기]

정리할때랑 시간이 지나서, 12~13분 걸렸다고 나오긴하는데, 사실상 난이도빨로 이게되나? 수준으로 밀어붙인 문제다. 

당연히 TimeLimit에서 걸릴줄 알았는데 그냥 accept 나오길래 다시풀수도있지만, 시간이 없으니 그냥 넘어간다.

그냥 생각한대로 코드 바로 쳐서 그냥 영타 수준으로 풀렸다.

앞에 wrong Answer 뜬거는 앞에 설명했듯이 정렬해서 넣었다가 저거 떠서 정렬빼고 서밋 넣은것이다.

 

5분컷문제.

반응형

'Algorithm > LeetCode' 카테고리의 다른 글

1679. Max Number of K-Sum Pairs  (0) 2023.07.25
11. Container With Most Water  (0) 2023.07.24
392. Is Subsequence  (0) 2023.07.20
443. String Compression  (0) 2023.07.18
334. Increasing Triplet Subsequence  (2) 2023.07.17
Comments