667. Beautiful Arrangement II
来源:互联网 发布:java 线程锁活锁 死锁 编辑:程序博客网 时间:2024/05/29 19:35
Given two integers n
and k
, you need to construct a list which contains n
different positive integers ranging from 1
to n
and obeys the following requirement:
Suppose this list is [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k
distinct integers.
If there are multiple answers, print any of them.
Example 1:
Input: n = 3, k = 1Output: [1, 2, 3]Explanation: The [1, 2, 3] has three different positive integers ranging from 1 to 3, and the [1, 1] has exactly 1 distinct integer: 1.
Example 2:
Input: n = 3, k = 2Output: [1, 3, 2]Explanation: The [1, 3, 2] has three different positive integers ranging from 1 to 3, and the [2, 1] has exactly 2 distinct integers: 1 and 2.
Note:
- The
n
andk
are in the range 1 <= k < n <= 104.
思路:果然不能直接DFS,会TLE
* 就是要想办法凑出k个来
* 注意到:1..n最多可以弄出n-1个不同的差,比如1..9就是
* 1 9 2 8 3 7 4 6 5
* diff: 8 7 6 5 4 3 2 1
* 是大小交替的,这样的话,只要先凑出k-1个,后面按照顺序来产生1就好了
注意下标控制
class Solution { public int[] constructArray(int n, int k) { int[] ret = new int[n]; int l = 1, r = n, i = 0; for(; i<k; i++) { if(i % 2 == 0)ret[i] = l++; elseret[i] = r--; } if(i % 2 == 1) for(int j=l; j<=r; j++)ret[i++] = j; else for(int j=r; j>=l; j--)ret[i++] = j; return ret; }}
阅读全文
0 0
- 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II。
- 667. Beautiful Arrangement II
- LeetCode 667. Beautiful Arrangement II
- leetcode 667. Beautiful Arrangement II
- LeetCode 667. Beautiful Arrangement II
- LeetCode 667. Beautiful Arrangement II
- leetcode 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II(Java)
- LeetCode 667. Beautiful Arrangement II
- leetcode 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II 找规律
- leetcode- Beautiful Arrangement II
- leetCode-Beautiful Arrangement II
- leetcode 667. Beautiful Arrangement II 双指针遍历
- PAT (Basic Level) Practise (中文) 1012. 数字分类 (20)
- ClassLoader.getSystemResource("log4j.properties")问题
- python快速搭建http服务
- C语言第五课
- 我怕写程序
- 667. Beautiful Arrangement II
- is-a&has-a
- AppDelegate警告 Initalizing 'AppDelegate * __strong'
- SharePreferences源码分析(SharedPreferencesImpl)
- 避免使用终结方法
- Istio: Traffic Management for your Microservices Practices
- JDBC
- Zerynth使用-1
- rails 数据验证(rails guides学习笔记)