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 ac81931

Browse files
solves #2784: Check if Array is Good in java
1 parent 220fa26 commit ac81931

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

‎README.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -839,7 +839,7 @@
839839
| 2765 | [Longest Alternating Subarray](https://leetcode.com/problems/longest-alternating-subarray) | [![Java](assets/java.png)](src/LongestAlternatingSubarray.java) | |
840840
| 2769 | [Find the Maximum Achievable Number](https://leetcode.com/problems/find-the-maximum-achievable-number) | [![Java](assets/java.png)](src/FindTheMaximumAchievableNumber.java) | |
841841
| 2778 | [Sum of Squares of Special Elements](https://leetcode.com/problems/sum-of-squares-of-special-elements) | [![Java](assets/java.png)](src/SumOfSquaresOfSpecialElements.java) | |
842-
| 2784 | [Check if Array is Good](https://leetcode.com/problems/check-if-array-is-good) | | |
842+
| 2784 | [Check if Array is Good](https://leetcode.com/problems/check-if-array-is-good) | [![Java](assets/java.png)](src/CheckIfArrayIsGood.java) | |
843843
| 2788 | [Split Strings by Separator](https://leetcode.com/problems/split-strings-by-separator) | | |
844844
| 2798 | [Number of Employees Who Met the Target](https://leetcode.com/problems/number-of-employees-who-met-the-target) | | |
845845
| 2806 | [Account Balance After Rounded Purchase](https://leetcode.com/problems/account-balance-after-rounded-purchase) | | |

‎src/CheckIfArrayIsGood.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// https://leetcode.com/problems/check-if-array-is-good
2+
// T: O(N)
3+
// S: O(N)
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
public class CheckIfArrayIsGood {
9+
public boolean isGood(int[] array) {
10+
final Map<Integer, Integer> frequencies = getFrequencies(array);
11+
for (int i = 1 ; i < array.length - 1 ; i++) {
12+
if (frequencies.getOrDefault(i, 0) != 1) {
13+
return false;
14+
}
15+
}
16+
return frequencies.getOrDefault(array.length - 1, 0) == 2;
17+
}
18+
19+
private Map<Integer, Integer> getFrequencies(int[] array) {
20+
final Map<Integer, Integer> result = new HashMap<>();
21+
for (int element : array) {
22+
result.put(element, result.getOrDefault(element, 0) + 1);
23+
}
24+
return result;
25+
}
26+
}

0 commit comments

Comments
(0)

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