Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions leetcode/2101-2200/2149.Rearrange-Array-Elements-by-Sign/README.md
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
# [2149.Rearrange Array Elements by Sign][title]

> [!WARNING|style:flat]
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)

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

You should **rearrange** the elements of nums such that the modified 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.

**Example 1:**

```
Input: a = "11", b = "1"
Output: "100"
Input: nums = [3,1,-2,-5,2,-4]
Output: [3,-2,1,-5,2,-4]
Explanation:
The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
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.
```

## 题意
> ...
**Example 2:**

## 题解

### 思路1
> ...
Rearrange Array Elements by Sign
```go
```

Input: nums = [-1,1]
Output: [1,-1]
Explanation:
1 is the only positive integer and -1 the only negative integer in nums.
So nums is rearranged to [1,-1].
```

## 结语

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(nums []int) []int {
l := len(nums)
neg := make([]int, l/2)
pos := make([]int, l/2)
ans := make([]int, l)
ai, bi := 0, 0
for _, n := range nums {
if n < 0 {
neg[ai] = n
ai++
continue
}
pos[bi] = n
bi++
}
for i := 0; i < l; i += 2 {
ans[i] = pos[i/2]
ans[i+1] = neg[i/2]
}
return ans
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs []int
expect []int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", []int{3, 1, -2, -5, 2, -4}, []int{3, -2, 1, -5, 2, -4}},
{"TestCase2", []int{-1, 1}, []int{1, -1}},
}

// 开始测试
Expand All @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
}
}

//压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

//使用案列
// 使用案列
func ExampleSolution() {
}