LeetCode 932. Beautiful Array (Medium)
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
方法:divide and conquer
思路:
1 首先观察到如果一个数是比如5,另一个数是6,那么就不存在A[k]使得A[k]*2 = A[i] + A[j]。
2 所以如果我们有一个部分的array是由odd构成,一个array是由even构成。在odd数组和even数组都是beautiful的前提下,merge成的数组也会是beautiful数组。
3 要如何保证odd数组和even数组是beautiful的呢,We can get the odd/even beautiful array from previous beautiful array by addition and multiplication。 所以我们可以在之前
得到的array的基础上,2*num-1得到下一个odd中的奇数,2*num得到偶数。
4 最后merge odd数组和even数组就可以。
time complexity:O(N) space complexity:O(N)
class Solution: def beautifulArray(self, N: int) -> List[int]: if N == 1: return [1] res = [1] while len(res) < N: res = [i * 2 - 1 for i in res] + [i * 2 for i in res] # print(res) return [i for i in res if i <= N]
浙公网安备 33010602011771号