932. Beautiful Array
2024-08-27 18:16:30
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)
最新文章
- 《DSP using MATLAB》第6章开始了
- javascript DOM 操作
- getattribute()与getparameter()的区别
- 基于DDD的.NET开发框架 - ABP领域服务
- 泛型约束 where T : class,new()
- 使用WebRequest 检测 手机号归属地。 C#通用 使用json 和可设定超时的WebClient
- MVC项目实践,在三层架构下实现SportsStore-08,部署到IIS服务器
- python 爬虫抓取心得
- 第五篇、Uber用视频播放做启动动画
- Android中SharedPreferences和序列化结合保存对象数据
- kafak 命令使用
- Trie树(字典树) 最热门的前N个搜索关键词
- 什么是 gnuplot
- appledoc导出iOS代码文档的使用和问题详解(干货篇)
- SCOI2019酱油记
- js中substr、substring、slice的区别
- jquery点击回到顶部
- Django 基模板布局设置
- swagger注释@API详细说明
- C#如何直接调用非托管代码
热门文章
- [hdu4347]The Closest M Points(线段树形式kd-tree)
- make: *** No rule to make target `build&#39;, needed by `default&#39;. Stop.
- centos6.5 svn服务端搭建
- AM使用指南:如何在Managed Bean中获取AM实例?
- Bigtable:一个分布式的结构化数据存储系统
- scala的隐式转换
- btrfs的介绍与使用
- OSAL的原理
- Redis初学笔记
- 一起做RGB-D SLAM (5)