932. Beautiful Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/83473033

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]
        

猜你喜欢

转载自blog.csdn.net/zjucor/article/details/83473033