---
# System prepended metadata

title: 'Leetcode [No. 2149] Rearrange Array Elements by Sign (MEDIUM) 解題心得'
tags: [leetcode]

---

# Leetcode [No. 2149] Rearrange Array Elements by Sign (MEDIUM)

+ Daily Challenge Solved on 2024/02/14 Valentines Day <3


+ 首先，這我...
    + ![image](https://hackmd.io/_uploads/S15G_Ctjp.png)



## 題目

這題因為不能調動pos在array中的順序，因此最簡單的做法就是把他們分成兩個array後再merge即可。


## 思路
+ 這個解法....
```c++=
class Solution {
public:
    vector<int> rearrangeArray(vector<int>& nums) {
        vector<int> res(nums.size());
        vector<int> pos;
        vector<int> neg;
        for(int i = 0 ; i < nums.size(); i++)
        {
            if(nums[i] > 0)
            {
                pos.emplace_back(nums[i]);
            }
            else
            {
                neg.emplace_back(nums[i]);
            }
        }

        // merge pos and neg as result
        for(int i = 0 ; i < nums.size(); i++)
        {
            if(i%2 == 0)
            {
                res[i]=(pos[i/2]);
            }
            else
            {
                res[i]=(neg[(i-1)/2]);
            }
        }
        return res;
    }
};
```

### 解法分析
+ time complexity: O(n)
+ Space complexity: O(n)


### 執行結果

![image](https://hackmd.io/_uploads/SyIYORtia.jpg)
