@@ -48,13 +48,91 @@ When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.
48
48
### ** Python3**
49
49
50
50
``` python
51
-
51
+ class Solution :
52
+ def rearrangeArray (self , nums : List[int ]) -> List[int ]:
53
+ nums.sort()
54
+ n = len (nums)
55
+ m = (n + 1 ) >> 1
56
+ ans = []
57
+ for i in range (m):
58
+ ans.append(nums[i])
59
+ if i + m < n:
60
+ ans.append(nums[i + m])
61
+ return ans
52
62
```
53
63
54
64
### ** Java**
55
65
56
66
``` java
67
+ class Solution {
68
+ public int [] rearrangeArray (int [] nums ) {
69
+ Arrays . sort(nums);
70
+ int n = nums. length;
71
+ int m = (n + 1 ) >> 1 ;
72
+ int [] ans = new int [n];
73
+ for (int i = 0 , j = 0 ; i < n; i += 2 , j++ ) {
74
+ ans[i] = nums[j];
75
+ if (j + m < n) {
76
+ ans[i + 1 ] = nums[j + m];
77
+ }
78
+ }
79
+ return ans;
80
+ }
81
+ }
82
+ ```
83
+
84
+ ### ** C++**
85
+
86
+ ``` cpp
87
+ class Solution {
88
+ public:
89
+ vector<int > rearrangeArray(vector<int >& nums) {
90
+ sort(nums.begin(), nums.end());
91
+ vector<int > ans;
92
+ int n = nums.size();
93
+ int m = (n + 1) >> 1;
94
+ for (int i = 0; i < m; ++i)
95
+ {
96
+ ans.push_back(nums[ i] );
97
+ if (i + m < n) ans.push_back(nums[ i + m] );
98
+ }
99
+ return ans;
100
+ }
101
+ };
102
+ ```
103
+
104
+ ### **Go**
105
+
106
+ ```go
107
+ func rearrangeArray(nums []int) []int {
108
+ sort.Ints(nums)
109
+ n := len(nums)
110
+ m := (n + 1) >> 1
111
+ var ans []int
112
+ for i := 0; i < m; i++ {
113
+ ans = append(ans, nums[i])
114
+ if i+m < n {
115
+ ans = append(ans, nums[i+m])
116
+ }
117
+ }
118
+ return ans
119
+ }
120
+ ```
57
121
122
+ ``` go
123
+ func rearrangeArray (nums []int ) []int {
124
+ rand.Seed (time.Now ().UnixNano ())
125
+ outer:
126
+ for {
127
+ rand.Shuffle (len (nums), func (i, j int ) { nums[i], nums[j] = nums[j], nums[i] })
128
+ for i := 1 ; i < len (nums)-1 ; i++ {
129
+ if nums[i]*2 == nums[i-1 ]+nums[i+1 ] {
130
+ continue outer
131
+ }
132
+ }
133
+ return nums
134
+ }
135
+ }
58
136
```
59
137
60
138
### ** ...**
0 commit comments