Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ebe4ea6

Browse files
fix(0135): 加了注释,比原先少一次遍历
1 parent f88678d commit ebe4ea6

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

‎problems/0135.分发糖果.md

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -132,30 +132,33 @@ public:
132132
Java:
133133
```java
134134
class Solution {
135+
/**
136+
分两个阶段
137+
1、起点下标1 从左往右,只要 右边 比 左边 大,右边的糖果=左边 + 1
138+
2、起点下标 ratings.length - 2 从右往左, 只要左边 比 右边 大,此时 左边的糖果应该 取本身的糖果数(符合比它左边大) 和 右边糖果数 + 1 二者的最大值,这样才符合 它比它左边的大,也比它右边大
139+
*/
135140
public int candy(int[] ratings) {
136-
int[] candy = new int[ratings.length];
137-
for (int i = 0; i < candy.length; i++) {
138-
candy[i] = 1;
139-
}
140-
141+
int[] candyVec = new int[ratings.length];
142+
candyVec[0] = 1;
141143
for (int i = 1; i < ratings.length; i++) {
142144
if (ratings[i] > ratings[i - 1]) {
143-
candy[i] = candy[i - 1] + 1;
145+
candyVec[i] = candyVec[i - 1] + 1;
146+
} else {
147+
candyVec[i] = 1;
144148
}
145149
}
146150
147151
for (int i = ratings.length - 2; i >= 0; i--) {
148152
if (ratings[i] > ratings[i + 1]) {
149-
candy[i] = Math.max(candy[i],candy[i + 1] + 1);
153+
candyVec[i] = Math.max(candyVec[i], candyVec[i + 1] + 1);
150154
}
151155
}
152156
153-
int count = 0;
154-
for (int i = 0; i < candy.length; i++) {
155-
count += candy[i];
157+
int ans = 0;
158+
for (int s : candyVec) {
159+
ans += s;
156160
}
157-
158-
return count;
161+
return ans;
159162
}
160163
}
161164
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /