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)

最新文章

  1. 《DSP using MATLAB》第6章开始了
  2. javascript DOM 操作
  3. getattribute()与getparameter()的区别
  4. 基于DDD的.NET开发框架 - ABP领域服务
  5. 泛型约束 where T : class,new()
  6. 使用WebRequest 检测 手机号归属地。 C#通用 使用json 和可设定超时的WebClient
  7. MVC项目实践,在三层架构下实现SportsStore-08,部署到IIS服务器
  8. python 爬虫抓取心得
  9. 第五篇、Uber用视频播放做启动动画
  10. Android中SharedPreferences和序列化结合保存对象数据
  11. kafak 命令使用
  12. Trie树(字典树) 最热门的前N个搜索关键词
  13. 什么是 gnuplot
  14. appledoc导出iOS代码文档的使用和问题详解(干货篇)
  15. SCOI2019酱油记
  16. js中substr、substring、slice的区别
  17. jquery点击回到顶部
  18. Django 基模板布局设置
  19. swagger注释@API详细说明
  20. C#如何直接调用非托管代码

热门文章

  1. [hdu4347]The Closest M Points(线段树形式kd-tree)
  2. make: *** No rule to make target `build&#39;, needed by `default&#39;. Stop.
  3. centos6.5 svn服务端搭建
  4. AM使用指南:如何在Managed Bean中获取AM实例?
  5. Bigtable:一个分布式的结构化数据存储系统
  6. scala的隐式转换
  7. btrfs的介绍与使用
  8. OSAL的原理
  9. Redis初学笔记
  10. 一起做RGB-D SLAM (5)