返回介绍

solution / 3000-3099 / 3046.Split the Array / README_EN

发布于 2024-06-17 01:02:57 字数 3395 浏览 0 评论 0 收藏 0

3046. Split the Array

中文文档

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.

 

Constraints:

  • 1 <= nums.length <= 100
  • nums.length % 2 == 0
  • 1 <= nums[i] <= 100

Solutions

Solution 1: Counting

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.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the length of the array.

class Solution:
  def isPossibleToSplit(self, nums: List[int]) -> bool:
    return max(Counter(nums).values()) < 3
class Solution {
  public boolean isPossibleToSplit(int[] nums) {
    int[] cnt = new int[101];
    for (int x : nums) {
      if (++cnt[x] >= 3) {
        return false;
      }
    }
    return true;
  }
}
class Solution {
public:
  bool isPossibleToSplit(vector<int>& nums) {
    int cnt[101]{};
    for (int x : nums) {
      if (++cnt[x] >= 3) {
        return false;
      }
    }
    return true;
  }
};
func isPossibleToSplit(nums []int) bool {
  cnt := [101]int{}
  for _, x := range nums {
    cnt[x]++
    if cnt[x] >= 3 {
      return false
    }
  }
  return true
}
function isPossibleToSplit(nums: number[]): boolean {
  const cnt: number[] = Array(101).fill(0);
  for (const x of nums) {
    if (++cnt[x] >= 3) {
      return false;
    }
  }
  return true;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文