Skip to content

Commit 189e886

Browse files
solves #2460: Apply Operations to an Array in java
1 parent f932595 commit 189e886

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -777,7 +777,7 @@
777777
| 2446 | [Determine if Two Events Have Conflict](https://leetcode.com/problems/determine-if-two-events-have-conflict) | [![Java](assets/java.png)](src/DetermineIfTwoEventsHaveConflict.java) | |
778778
| 2451 | [Odd String Difference](https://leetcode.com/problems/odd-string-difference) | [![Java](assets/java.png)](src/OddStringDifference.java) | |
779779
| 2455 | [Average Value of Even Numbers That Are Divisible by Three](https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three) | [![Java](assets/java.png)](src/AverageValueOfEvenNumbersThatAreDivisibleByThree.java) | |
780-
| 2460 | [Apply Operations to an Array](https://leetcode.com/problems/apply-operations-to-an-array) | | |
780+
| 2460 | [Apply Operations to an Array](https://leetcode.com/problems/apply-operations-to-an-array) | [![Java](assets/java.png)](src/ApplyOperationsToAnArray.java) | |
781781
| 2465 | [Number of Distinct Averages](https://leetcode.com/problems/number-of-distinct-averages) | | |
782782
| 2466 | [Count Ways To Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings) | | |
783783
| 2475 | [Number of Unequal Triplets in Array](https://leetcode.com/problems/number-of-unequal-triplets-in-array) | | |

src/ApplyOperationsToAnArray.java

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// https://leetcode.com/problems/apply-operations-to-an-array
2+
// T: O(N)
3+
// S: O(N)
4+
5+
public class ApplyOperationsToAnArray {
6+
public int[] applyOperations(int[] array) {
7+
final int[] result = new int[array.length];
8+
int j = 0;
9+
for (int i = 0, previous = array[0] ; i < array.length - 1 ; i++) {
10+
if (previous == 0) {
11+
previous = array[i + 1];
12+
continue;
13+
}
14+
15+
if (previous == array[i + 1]) {
16+
result[j++] = 2 * array[i];
17+
previous = 0;
18+
continue;
19+
}
20+
21+
result[j++] = array[i];
22+
previous = array[i + 1];
23+
}
24+
25+
if (array[array.length - 2] != array[array.length - 1]) {
26+
result[j] = array[array.length - 1];
27+
}
28+
29+
return result;
30+
}
31+
}

0 commit comments

Comments
 (0)