2149. Rearrange Array Elements by Sign Medium

@problem@discussion
#Array#Two Pointers#Simulation



1/**
2 * [2149] Rearrange Array Elements by Sign
3 *
4 * You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
5 * You should rearrange the elements of nums such that the modified array follows the given conditions:
6 * <ol>
7 * 	Every consecutive pair of integers have opposite signs.
8 * 	For all integers with the same sign, the order in which they were present in nums is preserved.
9 * 	The rearranged array begins with a positive integer.
10 * </ol>
11 * Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
12 *  
13 * Example 1:
14 * 
15 * Input: nums = [3,1,-2,-5,2,-4]
16 * Output: [3,-2,1,-5,2,-4]
17 * Explanation:
18 * The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
19 * The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
20 * Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.  
21 * 
22 * Example 2:
23 * 
24 * Input: nums = [-1,1]
25 * Output: [1,-1]
26 * Explanation:
27 * 1 is the only positive integer and -1 the only negative integer in nums.
28 * So nums is rearranged to [1,-1].
29 * 
30 *  
31 * Constraints:
32 * 
33 * 	2 <= nums.length <= 2 * 10^5
34 * 	nums.length is even
35 * 	1 <= |nums[i]| <= 10^5
36 * 	nums consists of equal number of positive and negative integers.
37 * 
38 */
39pub struct Solution {}
40
41// problem: https://leetcode.com/problems/rearrange-array-elements-by-sign/
42// discuss: https://leetcode.com/problems/rearrange-array-elements-by-sign/discuss/?currentPage=1&orderBy=most_votes&query=
43
44// submission codes start here
45
46impl Solution {
47    pub fn rearrange_array(nums: Vec<i32>) -> Vec<i32> {
48        vec![]
49    }
50}
51
52// submission codes end
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn test_2149() {
60    }
61}
62


Back
© 2025 bowen.ge All Rights Reserved.