63
63
64
64
<!-- 这里可写通用的实现逻辑 -->
65
65
66
+ ** 方法一:暴力枚举**
67
+
68
+ 时间复杂度 $O(n^2)$。
69
+
70
+ ** 方法二:贪心**
71
+
66
72
<!-- tabs:start -->
67
73
68
74
### ** Python3**
@@ -80,6 +86,20 @@ class Solution:
80
86
return ans
81
87
```
82
88
89
+ ``` python
90
+ class Solution :
91
+ def maxDistance (self , colors : List[int ]) -> int :
92
+ n = len (colors)
93
+ if colors[0 ] != colors[- 1 ]:
94
+ return n - 1
95
+ i, j = 1 , n - 2
96
+ while colors[i] == colors[0 ]:
97
+ i += 1
98
+ while colors[j] == colors[0 ]:
99
+ j -= 1
100
+ return max (n - i - 1 , j)
101
+ ```
102
+
83
103
### ** Java**
84
104
85
105
<!-- 这里可写当前语言的特殊实现逻辑 -->
@@ -100,6 +120,21 @@ class Solution {
100
120
}
101
121
```
102
122
123
+ ``` java
124
+ class Solution {
125
+ public int maxDistance (int [] colors ) {
126
+ int n = colors. length;
127
+ if (colors[0 ] != colors[n - 1 ]) {
128
+ return n - 1 ;
129
+ }
130
+ int i = 0 , j = n - 1 ;
131
+ while (colors[++ i] == colors[0 ]);
132
+ while (colors[-- j] == colors[0 ]);
133
+ return Math . max(n - i - 1 , j);
134
+ }
135
+ }
136
+ ```
137
+
103
138
### ** C++**
104
139
105
140
``` cpp
@@ -116,6 +151,20 @@ public:
116
151
};
117
152
```
118
153
154
+ ```cpp
155
+ class Solution {
156
+ public:
157
+ int maxDistance(vector<int>& colors) {
158
+ int n = colors.size();
159
+ if (colors[0] != colors[n - 1]) return n - 1;
160
+ int i = 0, j = n;
161
+ while (colors[++i] == colors[0]);
162
+ while (colors[--j] == colors[0]);
163
+ return max(n - i - 1, j);
164
+ }
165
+ };
166
+ ```
167
+
119
168
### ** Go**
120
169
121
170
``` go
@@ -146,6 +195,30 @@ func abs(x int) int {
146
195
}
147
196
```
148
197
198
+ ``` go
199
+ func maxDistance (colors []int ) int {
200
+ n := len (colors)
201
+ if colors[0 ] != colors[n-1 ] {
202
+ return n - 1
203
+ }
204
+ i , j := 1 , n-2
205
+ for colors[i] == colors[0 ] {
206
+ i++
207
+ }
208
+ for colors[j] == colors[0 ] {
209
+ j--
210
+ }
211
+ return max (n-i-1 , j)
212
+ }
213
+
214
+ func max (a , b int ) int {
215
+ if a > b {
216
+ return a
217
+ }
218
+ return b
219
+ }
220
+ ```
221
+
149
222
### ** ...**
150
223
151
224
```
0 commit comments