avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

3046. Split the Array

  2025-01-05        
字数统计: 297字   |   阅读时长: 1min

Description:

You are given an integer array nums of even length. You have to split the array into two parts nums1 and nums2 such that:

nums1.length == nums2.length == nums.length / 2.
nums1 should contain distinct elements.
nums2 should also contain distinct elements.
Return true if it is possible to split the array, and false otherwise.

Example 1:

Input: nums = [1,1,2,2,3,4]
Output: true
Explanation: One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].
Example 2:

Input: nums = [1,1,1,1]
Output: false
Explanation: The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.

Thinking:

题目要求判断是否可以将数组分成两个部分,使得两个部分的元素都是不同的。
最开始考虑的是Counter()记录每个数字是否满足某个条件,如果不满足就返回False。后面发现不需要Counter,普通的字典记录,中途遇到某个数字大于2就返回False即可。

Code:

O(2n)
1
2
3
4
5
6
7
8
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
Counter_nums = Counter(nums)
for i, j in Counter_nums.items():
if j > 2:
return False
else:
return True
O(n)
1
2
3
4
5
6
7
8
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
count = {}
for num in nums:
count[num] = count.get(num, 0) + 1
if count[num] > 2:
return False
return True

扫一扫,分享到微信

微信分享二维码
3138. Minimum Length of Anagram Concatenation
1366. Rank Teams by Votes
目录
  1. 1. Description:
  2. 2. Thinking:
  3. 3. Code:

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号