본문 바로가기
코딩테스트

C++ ] leetCode 2161 - Partition Array According to Given Pivot

by eteo 2024. 3. 8.

 

 

 

리트코드 2161 문제

 

You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:

 

  • Every element less than pivot appears before every element greater than pivot.
  • Every element equal to pivot appears in between the elements less than and greater than pivot.
  • The relative order of the elements less than pivot and the elements greater than pivot is maintained.
  • More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj.

 

Return nums after the rearrangement.

 

 

Example 1:

  • Input: nums = [9,12,5,10,14,3,10], pivot = 10
  • Output: [9,5,3,10,10,12,14]
  • Explanation: The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array. The elements 12 and 14 are greater than the pivot so they are on the right side of the array. The relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.

 

 

Example 2:

  • Input: nums = [-3,4,3,2], pivot = 2
  • Output: [-3,2,4,3]
  • Explanation: The element -3 is less than the pivot so it is on the left side of the array. The elements 4 and 3 are greater than the pivot so they are on the right side of the array. The relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.

 

 

Constraints:

  • 1 <= nums.length <= 105
  • -106 <= nums[i] <= 106
  • pivot equals to an element of nums.

 

 

nums.size() 만큼 순회하면서 등장 순서대로 pivot보다 작은 숫자는 less 벡터에 넣고 pivot보다 큰 숫자는 greater 벡터에 넣는다.

 

다시 nums.size() 만큼 순회하면서 less 벡터의 요소, pivot 그리고 greater 벡터의 요소를 nums[i]에 대입하면 되고 pivot이 대입될 위치 i는 (i >= less.size() && i < nums.size() - greater.size()) 로 알 수 있다.

 

 

class Solution {
public:
    vector<int> pivotArray(vector<int>& nums, int pivot) {
        vector<int> less;
        vector<int> greater;

        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] < pivot) {
                less.push_back(nums[i]);
            }
            if(nums[i] > pivot) {
                greater.push_back(nums[i]);
            }
        }

        int i = 0, j = 0;
        while(i < nums.size()) {
            if(i < less.size()) {
                nums[i] = less[i];
            }
            else if( i < (nums.size() - greater.size())) {
                nums[i] = pivot;                
            }
            else {
                nums[i] = greater[j++];
            }
            i++;
        }

        return nums;
    }
};