932. Beautiful Array

For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:

For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].

Given N, return any beautiful array A.  (It is guaranteed that one exists.)

 

Example 1:

Input: 4
Output: [2,1,4,3]

Example 2:

Input: 5
Output: [3,1,2,5,4]

 

Note:

  • 1 <= N <= 1000

思路:

比赛想到的时候是分成2部分,前面一部分,后面一部分,然后尽量2者组合不会有问题,这样的话就可以分治到2边,偶数还好办,但是奇数就卡住了。

后面看题解:不要分前半部分后半部分,直接分奇数偶数

One way is to divide into [1, N / 2] and [N / 2 + 1, N]. But it will cause problems when we merge them.

Another way is to divide into odds part and evens part. So there is no k with A[k] * 2 = odd + even

需要注意的是:对一个符合条件的数组里面所有的数进行同一个操作,仍然是满足条件的。这也是为什么能分治的条件

class Solution:
    def beautifulArray(self, N):
        """
        :type N: int
        :rtype: List[int]
        """
        if N==1: return [1]
        
        l=self.beautifulArray(N//2)
        r=self.beautifulArray(N-N//2)
        return [i*2 for i in l]+[i*2-1 for i in r]
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值