加载中...
1968-构造元素不等于两相邻元素平均值的数组(Array With Elements Not Equal to Average of Neighbors)
发表于:2021-12-03 | 分类: 中等
字数统计: 745 | 阅读时长: 3分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/array-with-elements-not-equal-to-average-of-neighbors

英文原文

You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.

More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].

Return any rearrangement of nums that meets the requirements.

 

Example 1:

Input: nums = [1,2,3,4,5]
Output: [1,2,4,5,3]
Explanation:
When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.

Example 2:

Input: nums = [6,2,0,9,7]
Output: [9,7,6,2,0]
Explanation:
When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.

 

Constraints:

  • 3 <= nums.length <= 105
  • 0 <= nums[i] <= 105

中文题目

给你一个 下标从 0 开始 的数组 nums ,数组由若干 互不相同的 整数组成。你打算重新排列数组中的元素以满足:重排后,数组中的每个元素都 不等于 其两侧相邻元素的 平均值

更公式化的说法是,重新排列的数组应当满足这一属性:对于范围 1 <= i < nums.length - 1 中的每个 i(nums[i-1] + nums[i+1]) / 2 不等于 nums[i] 均成立 。

返回满足题意的任一重排结果。

 

示例 1:

输入:nums = [1,2,3,4,5]
输出:[1,2,4,5,3]
解释:
i=1, nums[i] = 2, 两相邻元素平均值为 (1+4) / 2 = 2.5
i=2, nums[i] = 4, 两相邻元素平均值为 (2+5) / 2 = 3.5
i=3, nums[i] = 5, 两相邻元素平均值为 (4+3) / 2 = 3.5

示例 2:

输入:nums = [6,2,0,9,7]
输出:[9,7,6,2,0]
解释:
i=1, nums[i] = 7, 两相邻元素平均值为 (9+6) / 2 = 7.5
i=2, nums[i] = 6, 两相邻元素平均值为 (7+2) / 2 = 4.5
i=3, nums[i] = 2, 两相邻元素平均值为 (6+0) / 2 = 3

 

提示:

  • 3 <= nums.length <= 105
  • 0 <= nums[i] <= 105

通过代码

高赞题解

解题思路

由于数组中元素各不相同,故满足 (nums[i-1] + nums[i+1]) / 2 == nums[i] 的条件必须是连续3个元素依次增大,或者依次减小。

那么打破这条规则即可

如何打破:

构造数组中元素为 [小,大,小,大,小,大] 的形式即可打破

代码

class Solution {
public:
    vector<int> rearrangeArray(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        for (int i = 1; i < nums.size() - 1; i += 2) swap(nums[i + 1], nums[i]);
        return nums;
    }
};

统计信息

通过次数 提交次数 AC比率
4824 13359 36.1%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
1955-统计特殊子序列的数目(Count Number of Special Subsequences)
下一篇:
1974-使用特殊打字机键入单词的最少时间(Minimum Time to Type Word Using Special Typewriter)
本文目录
本文目录