[Lintcode] 932. Beautiful Array

Leetcode:932. Beautiful Array

  • 本题难度: Hard
  • Topic: divide-and-conquer

Description

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

我的代码


import copy
import collections
class Solution:
    def beautifulArray(self,N):
        memo = {1: [1]}
        def f(N):
            if N not in memo:
                odds = f((N+1)//2)
                evens = f(N//2)
                memo[N] = [2*x-1 for x in odds] + [2*x for x in evens]
            return memo[N]
        return f(N)

超时的代码


noUse = {i+1 for i in range(N)}
use = collections.OrderedDict()
stack = [[use,noUse]]
while(len(stack)>0):
    [used_dic, nouse_set] = stack.pop()
    if len(nouse_set) == 0:
        return [item for item in used_dic]
    for toUse in nouse_set:
        f = 0
        for used in used_dic:
            tmp = used_dic.get((used+toUse)//2,-1)
            if tmp>used_dic[used]:
                f = 1
                break
            if toUse*2-used in nouse_set:
                f = 1
                break
        if f == 1:
            continue
        tmp_set = copy.copy(nouse_set)
        tmp_set.remove(toUse)
        tmp_dic = copy.copy(used_dic)
        tmp_dic[toUse] = len(used_dic)-1
        stack.append([tmp_dic,tmp_set])

思路

分治的思想,对左右半边来说,第一个数只取左边,第二个数只取右边,如果左右两边,一边奇数,一边偶数,则其平均数不会出现。

posted @ 2019-07-27 14:47  siriusli  阅读(126)  评论(0编辑  收藏  举报