[코테 풀이] Rearrange Array Elements by Sign

시내·2024년 6월 27일

Q_2149) Rearrange Array Elements by Sign

출처 : https://leetcode.com/problems/rearrange-array-elements-by-sign/

You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.

You should return the array of nums such that the the array follows the given conditions:

  1. Every consecutive pair of integers have opposite signs.

  2. For all integers with the same sign, the order in which they were present in nums is preserved.

  3. The rearranged array begins with a positive integer.

Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

class Solution {
    public int[] rearrangeArray(int[] nums) {
        int[] answer = new int[nums.length];
        int[] plus = new int[nums.length / 2], minus = new int[nums.length / 2];
        int pInd = 0, mInd = 0, answerInd = 0, count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) plus[pInd++] = nums[i];
            else minus[mInd++] = nums[i];
        }

        while (count < nums.length / 2) {
            answer[answerInd++] = plus[count];
            answer[answerInd++] = minus[count];
            count++;
        }
        return answer;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글