• (分治法)leetcode 932. Beautiful Array


    题意:A是一个从1到N的全排列数组,对于每个A里的元素,都不存在 i<k<j 时, A[k]*2 = A[i] * A[j] 

    解法一:迭代

    C++

    class Solution {
    public:
        vector<int> beautifulArray(int N) {
            vector<int> res = {1};
            while(res.size()<N){
                vector<int> temp;
                for(auto x: res){
                    if(x*2-1<=N)
                        temp.push_back(x*2-1);
                }
                for(auto x: res){
                    if(x*2<=N)
                        temp.push_back(x*2);
                }
                //swap(temp, res);
                res = temp;
            }
            return res;
        }
    };

    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]

     解法二:递归, 个数为N的序列中,奇数的个数为(N+1)/2, 偶数的个数为N/2,故beautifulArray(N) 由 beautifulArray(N/2) + beautifulArray(N/2)

    Python:

    class Solution(object):
        def beautifulArray(self, N):
            """
            :type N: int
            :rtype: List[int]
            """
            if(N==1):
                return [1]
            # N为偶 N%2为0;N为奇 N%2为1
            odd = [i*2-1 for i in self.beautifulArray(N/2 + N%2)]
            even = [i*2 for i in self.beautifulArray(N/2)]
            
            return odd+even

    C++

    class Solution {
    public:
        vector<int> beautifulArray(int N) {
            vector<int> res;
            if(N==1){
                res.push_back(1);
                return res;
            }
            vector<int> temp;
            temp = beautifulArray((N+1)/2);
            for(auto a: temp)
                res.push_back(a*2-1);
            temp = beautifulArray(N/2);
            for(auto a:temp)
                res.push_back(a*2);
            
            return res;
        }
    };
  • 相关阅读:
    3.node.js AssertionError: false == true错误解决
    9.获取当前时区时间和utc时间的工具方法
    2.Express封装mysq方法
    1.Express初识
    poj 3617
    前缀和
    pop 反序列化
    Reverse前两个题
    前两个Web题
    Misc
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11226825.html
Copyright © 2020-2023  润新知