返回介绍

solution / 2700-2799 / 2740.Find the Value of the Partition / README_EN

发布于 2024-06-17 01:03:00 字数 3399 浏览 0 评论 0 收藏 0

2740. Find the Value of the Partition

中文文档

Description

You are given a positive integer array nums.

Partition nums into two arrays, nums1 and nums2, such that:

  • Each element of the array nums belongs to either the array nums1 or the array nums2.
  • Both arrays are non-empty.
  • The value of the partition is minimized.

The value of the partition is |max(nums1) - min(nums2)|.

Here, max(nums1) denotes the maximum element of the array nums1, and min(nums2) denotes the minimum element of the array nums2.

Return _the integer denoting the value of such partition_.

 

Example 1:

Input: nums = [1,3,2,4]
Output: 1
Explanation: We can partition the array nums into nums1 = [1,2] and nums2 = [3,4].
- The maximum element of the array nums1 is equal to 2.
- The minimum element of the array nums2 is equal to 3.
The value of the partition is |2 - 3| = 1. 
It can be proven that 1 is the minimum value out of all partitions.

Example 2:

Input: nums = [100,1,10]
Output: 9
Explanation: We can partition the array nums into nums1 = [10] and nums2 = [100,1].
- The maximum element of the array nums1 is equal to 10.
- The minimum element of the array nums2 is equal to 1.
The value of the partition is |10 - 1| = 9.
It can be proven that 9 is the minimum value out of all partitions.

 

Constraints:

  • 2 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Solutions

Solution 1

class Solution:
  def findValueOfPartition(self, nums: List[int]) -> int:
    nums.sort()
    return min(b - a for a, b in pairwise(nums))
class Solution {
  public int findValueOfPartition(int[] nums) {
    Arrays.sort(nums);
    int ans = 1 << 30;
    for (int i = 1; i < nums.length; ++i) {
      ans = Math.min(ans, nums[i] - nums[i - 1]);
    }
    return ans;
  }
}
class Solution {
public:
  int findValueOfPartition(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int ans = 1 << 30;
    for (int i = 1; i < nums.size(); ++i) {
      ans = min(ans, nums[i] - nums[i - 1]);
    }
    return ans;
  }
};
func findValueOfPartition(nums []int) int {
  sort.Ints(nums)
  ans := 1 << 30
  for i, x := range nums[1:] {
    ans = min(ans, x-nums[i])
  }
  return ans
}

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

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

发布评论

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