【Leetcode】667. 数组相邻差值的个数(Beautiful Arrangement II)

Leetcode - 667 Beautiful Arrangement II (Medium)

题目描述:数组元素的取值范围为[1, n],构建新的数组,使得相邻元素差值不相同的个数为 k。

Input: n = 3, k = 1
Output: [1, 2, 3]
Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.

解题思路:

当 n 为 9,k 为 8 时,可以构建数组,数组长度为 n 时,k 的最大值为 n - 1。

i: 1   2   3   4   5
j:   9   8   7   6
out: 1 9 2 8 3 7 4 6 5
dif:  8 7 6 5 4 3 2 1

当 k 为 5 时,可以构造:

     i++ j-- i++ j--  i++ i++ i++ ...
out: 1   9   2   8    3   4   5   6   7
dif:   8   7   6   5    1   1   1   1 
public int[] constructArray(int n, int k) {
    int[] res = new int[n];
    for (int i = 0, l = 1, r = n; l <= r; i++)
        res[i] = k > 1 ? (k-- % 2 != 0 ? l++ : r--) : l++;
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值