Skip to content

Commit ee0832d

Browse files
solves build an array with stack operations
1 parent a69de4a commit ee0832d

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@
366366
| 1431 | [Kids With The Greatest Number Of Candies](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies) | [![Java](assets/java.png)](src/KidsWithTheGreatestNumberOfCandies.java) | |
367367
| 1436 | [Destination City](https://leetcode.com/problems/destination-city) | [![Java](assets/java.png)](src/DestinationCity.java) | |
368368
| 1437 | [Check If All 1's Are at Least Length K Places Away](https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away) | [![Java](assets/java.png)](src/CheckIfAll1sAreAtLeastKPlacesAway.java) | |
369-
| 1441 | [Build An Array With Stack Operation](https://leetcode.com/problems/build-an-array-with-stack-operations) | | |
369+
| 1441 | [Build An Array With Stack Operation](https://leetcode.com/problems/build-an-array-with-stack-operations) | [![Java](assets/java.png)](src/BuildAnArrayWithStackOperations.java) | |
370370
| 1446 | [Consecutive Characters](https://leetcode.com/problems/consecutive-characters) | | |
371371
| 1450 | [Number of Students Doing Homework at Given Time](https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time) | | |
372372
| 1455 | [Check If Word Occurs as Prefix of any Word in Sentence](https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence) | | |
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class BuildAnArrayWithStackOperations {
5+
private static final String PUSH = "Push";
6+
private static final String POP = "Pop";
7+
8+
public List<String> buildArray(int[] target, int n) {
9+
List<String> result = new ArrayList<>();
10+
for (int index = 0, lastNumber = 0 ; index < target.length ; index++) {
11+
popKNumbers(result, target[index] - 1 - lastNumber);
12+
pushCurrentNumber(result);
13+
lastNumber = target[index];
14+
}
15+
return result;
16+
}
17+
18+
private void popKNumbers(List<String> list, int k) {
19+
while (k-- > 0) {
20+
list.add(PUSH);
21+
list.add(POP);
22+
}
23+
}
24+
25+
private void pushCurrentNumber(List<String> list) {
26+
list.add(PUSH);
27+
}
28+
}

0 commit comments

Comments
 (0)