1968 构造元素不等于两相邻元素平均值的数组

题目描述:
给你一个 下标从 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

方法1:
主要思路:解题链接汇总
(1)先对原来的数组进行排序;
(2)然后将排序后的数组一个当前最小值,一个当前最大值的方式,逐个的放入到新的数组中;

class Solution {
public:
    vector<int> rearrangeArray(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        vector<int> res(nums.size());
        int lhs=0,rhs=nums.size()-1;
        int index=0;
        while(lhs<=rhs){
            res[index++]=nums[lhs];
            if(lhs==rhs){
                break;
            }
            res[index++]=nums[rhs];
            ++lhs;
            --rhs;
        }
        return res;
    }
};

go语言实现

func rearrangeArray(nums []int) []int {
    sort.Ints(nums)
    res := make([]int,len(nums))
    lhs ,rhs := 0,len(nums)-1
    index := 0
    for lhs <= rhs {
        res[index]=nums[lhs]
        index++
        if lhs==rhs {
            break
        }
        res[index]=nums[rhs]
        index++
        lhs++
        rhs--
    }
    return res
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值