题目链接:https://leetcode.com/problems/beautiful-arrangement-ii/description/
难度:中
题目描述:
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 = 1 Output: [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 = 2 Output: [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.
解释:题目给定了两个整数n和k,要求创建一个含有n个正整数的数组,数组中的元素取值范围为1-n。并在构造的过程中遵守一定的规则,即数组中的元素两两相减之后得到k个不同的整数值
思路:这道题看起来要考虑的东西比较多,但其实说到底就是一道规律题,首先要明确的是,1-n个正整数两两相减最大有n-1种可能。即每次把最大的和最小的两个数取出做差,就可以得到n-1种不同的差。这样想来就十分简单了,通过取最大和最小凑出k-1种情况,后面的情况按照顺序排序(差为1)即可。
代码:
class Solution {
public:
vector<int> constructArray(int n, int k) {
vector<int> res;
int small = 1, large = n;
while (small <= large) {
if (k > 1) {
int cur = (k % 2 == 0 ? small++ : large--);
res.push_back(cur);
k--;
} else {
res.push_back(large--);
}
}
return res;
}
};
1.k分奇偶
2.规律找的不清晰,无法实现可以编成程序的思路。
暂时放到这,我会回来的。。。
日期:2018/2/11-22:16