|
44 | 44 |
|
45 | 45 | ## Solutions
|
46 | 46 |
|
47 | | -### Solution 1 |
| 47 | +### Solution 1: Counting |
| 48 | + |
| 49 | +According to the problem, we need to divide the array into two parts, and the elements in each part are all distinct. Therefore, we can count the occurrence of each element in the array. If an element appears three or more times, it cannot satisfy the problem's requirements. Otherwise, we can divide the array into two parts. |
| 50 | + |
| 51 | +The time complexity is $O(n),ドル and the space complexity is $O(n)$. Where $n$ is the length of the array. |
48 | 52 |
|
49 | 53 | <!-- tabs:start -->
|
50 | 54 |
|
51 | 55 | ```python
|
52 | | - |
| 56 | +class Solution: |
| 57 | + def isPossibleToSplit(self, nums: List[int]) -> bool: |
| 58 | + return max(Counter(nums).values()) < 3 |
53 | 59 | ```
|
54 | 60 |
|
55 | 61 | ```java
|
56 | | - |
| 62 | +class Solution { |
| 63 | + public boolean isPossibleToSplit(int[] nums) { |
| 64 | + int[] cnt = new int[101]; |
| 65 | + for (int x : nums) { |
| 66 | + if (++cnt[x] >= 3) { |
| 67 | + return false; |
| 68 | + } |
| 69 | + } |
| 70 | + return true; |
| 71 | + } |
| 72 | +} |
57 | 73 | ```
|
58 | 74 |
|
59 | 75 | ```cpp
|
60 | | - |
| 76 | +class Solution { |
| 77 | +public: |
| 78 | + bool isPossibleToSplit(vector<int>& nums) { |
| 79 | + int cnt[101]{}; |
| 80 | + for (int x : nums) { |
| 81 | + if (++cnt[x] >= 3) { |
| 82 | + return false; |
| 83 | + } |
| 84 | + } |
| 85 | + return true; |
| 86 | + } |
| 87 | +}; |
61 | 88 | ```
|
62 | 89 |
|
63 | 90 | ```go
|
| 91 | +func isPossibleToSplit(nums []int) bool { |
| 92 | + cnt := [101]int{} |
| 93 | + for _, x := range nums { |
| 94 | + cnt[x]++ |
| 95 | + if cnt[x] >= 3 { |
| 96 | + return false |
| 97 | + } |
| 98 | + } |
| 99 | + return true |
| 100 | +} |
| 101 | +``` |
64 | 102 |
|
| 103 | +```ts |
| 104 | +function isPossibleToSplit(nums: number[]): boolean { |
| 105 | + const cnt: number[] = Array(101).fill(0); |
| 106 | + for (const x of nums) { |
| 107 | + if (++cnt[x] >= 3) { |
| 108 | + return false; |
| 109 | + } |
| 110 | + } |
| 111 | + return true; |
| 112 | +} |
65 | 113 | ```
|
66 | 114 |
|
67 | 115 | <!-- tabs:end -->
|
|
0 commit comments