zoukankan      html  css  js  c++  java
  • 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

    Approach #1: divide and conquer. [C++]

    class Solution {
    public:
        vector<int> beautifulArray(int N) {
            vector<int> ans;
            ans.push_back(1);
            while (ans.size() < N) {
                vector<int> temp;
                for (int i : ans) if (i * 2 - 1 <= N) temp.push_back(i*2-1);
                for (int i : ans) if (i * 2 <= N) temp.push_back(i*2);
                ans = temp;
            }
            return ans;
        }
    };
    

      

    Approach #2: [Python]

    class Solution(object):
        def beautifulArray(self, N):
            """
            :type N: int
            :rtype: List[int]
            """
            res = [1]
            while len(res) < N:
                res = [i * 2 - 1 for i in res] + [i * 2 for i in res]
            return [i for i in res if i <= N]
    

      

    Analysis:

    https://leetcode.com/problems/beautiful-array/discuss/186679/C%2B%2BJavaPython-Odd-%2B-Even-Pattern-O(N)

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Spring 拦截器postHandle无法修改Response的原因
    使用AShot进行网页全页截图
    60句简短的话 句句在理
    天使
    路过青春的合欢树
    Velocity日期格式化
    高斯模糊的Java实现
    MyBatis架构与源码分析<资料收集>
    柳青(Jean)英文演讲集合
    hive sql 常见异常
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10344360.html
Copyright © 2011-2022 走看看