Hope Everyone Is Happy

[Easy] - 905. Sort Array By Parity (C++) 본문

※ 릿코드 ( LeetCode )/[C++] 문제 풀이 ( Solve the problems )

[Easy] - 905. Sort Array By Parity (C++)

J 크 2023. 1. 11. 23:30
728x90
반응형

https://leetcode.com/problems/sort-array-by-parity/description/

 

Sort Array By Parity - LeetCode

Sort Array By Parity - Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition.   Example 1: Input: nums = [3,1,2,4] Output: [2,4,3,1] Explanati

leetcode.com

 커리큘럼을 따라 In-place 예제 문제들을 풀고 있는데 역시 예제라 그런지 다 비슷비슷하네요! 예제 중 마지막 문제를 추가로 포스팅 해보겠습니다.

 

 문제의 조건 중 핵심 사항들을 정리하면 아래와 같습니다.

▶  입력된 배열안의 val 값과 동일한 원소는 delete (or 배열의 뒤로)

▶  val값 외 원소의 순서는 무관

▶  val값을 제외한 원소의 갯수 return

▶ Example )

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

 

https://heih.tistory.com/5

 

[Easy] - 283. Move Zeroes (C++)

https://leetcode.com/problems/move-zeroes/description/ Move Zeroes - LeetCode Move Zeroes - 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 withou

heih.tistory.com

 

 해결하는 방법은 위와 동일합니다.위의 문제와 비슷하게 입력된 배열의 ReadPointer 번째 인덱스가 입력된 val값이 아닐 경우0부터 시작되는 WritePointer번째 인덱스에 값을 넣어주며, 넣어준 후 WritePointer의 index를 1씩 증가시켜 주는 형태로 반복합니다. 배열의 사이즈 만큼 반복이 끝나면 배열의 앞에서부터 val값이 아닌 원소들로 순서대로 채워지게 됩니다.

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int nWritePointer = 0;

        for(int i = 0; i < nums.size();i++) {
            if(nums[i] != val)
                nums[nWritePointer++] = nums[i];
        }
        
        return nWritePointer;
    }
};

 

 그래도 Opencv 랑 MFC만 주구장창 보다가 이렇게 문제들을 풀어보니까 또 색다른 재미가 있네요. 모든 개발자 분들 화이팅입니다!!