LeetCode #3072

Distribute Elements Into Two Arrays II

1개의 풀이 · C++

문제 원문 보기 ↗

SOLUTION INFO

C++ · main.cpp

main.cpp
struct Segment {
    vector<int> tree;
    int siz;

    Segment(int N = 1 << 17) {
        for(siz = 1; siz <= N; siz <<= 1);
        tree.resize(siz << 1);
    }
    void update(int idx) {
        tree[idx += siz] ++;
        while(idx >>= 1) tree[idx] = merge(tree[idx << 1], tree[idx << 1 | 1]);
    }
    int query(int l, int r, int s, int e, int pos) {
        if(s <= l && r <= e) return tree[pos];
        if(e < l || r < s) return 0;
        int mid = (l + r) / 2;
        return merge(query(l, mid, s, e, pos << 1), query(mid + 1, r, s, e, pos << 1 | 1));
    }
    int query(int s, int e) { return query(0, siz - 1, s, e, 1); }
    int merge(int a, int b) { return a + b; }
};

class Solution {
public:
    vector<int> resultArray(vector<int>& nums) {
        vector<int> compress = nums;
        sort(compress.begin(), compress.end());
        compress.erase(unique(compress.begin(), compress.end()), compress.end());
        int K = compress.size(), N = nums.size();
        for(int &x: nums) x = lower_bound(compress.begin(), compress.end(), x) - compress.begin();
        Segment seg1(K + 1), seg2(K + 1);
        vector<int> V, W, answer;
        V.push_back(compress[nums[0]]); W.push_back(compress[nums[1]]);
        seg1.update(nums[0]); seg2.update(nums[1]);
        for(int i = 2; i < N; ++i) {
            int L = seg1.query(nums[i] + 1, K);
            int R = seg2.query(nums[i] + 1, K);
            if(L == R) {
                if(V.size() > W.size()) W.push_back(compress[nums[i]]), seg2.update(nums[i]);
                else V.push_back(compress[nums[i]]), seg1.update(nums[i]);
            }
            else if(L > R) {
                V.push_back(compress[nums[i]]);
                seg1.update(nums[i]);
            }
            else {
                W.push_back(compress[nums[i]]);
                seg2.update(nums[i]);
            }
        }
        for(const int &x: V) answer.push_back(x);
        for(const int &x: W) answer.push_back(x);
        return answer;
    }
};

SOLUTION DESCRIPTION

풀이 설명

등록된 풀이 설명이 없습니다.

GITHUB COMMUNITY

커뮤니티 평가

GitHub 계정으로 남긴 최신 평가 1건만 반영하며, 데이터는 매일 저장소에 동기화됩니다.

최근 동기화

체감 난이도

아직 평가 없음

첫 난이도 평가를 남겨주세요.

문제 추천

아직 평가 없음

이 문제가 도움이 되었는지 알려주세요.

이 문제 평가하기

GitHub 로그인 후 난이도를 제출하고, 원하는 경우 추천 여부도 함께 남길 수 있습니다.

추천 여부 (선택)

평가하려면 GitHub로 로그인해 주세요.

평가는 자동으로 저장소 Discussion에 기록되므로 Discussion 화면을 직접 열 필요가 없습니다. 같은 문제를 다시 평가하면 기존 평가가 갱신됩니다.

DISCUSSION

댓글

GitHub 로그인 후 작성할 수 있으며 모든 댓글은 이 저장소의 Discussions에 보관됩니다.