题目:
Given two integers
n
andk
, you need to construct a list which containsn
different positive integers ranging from1
ton
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 exactlyk
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 and k are in the range 1 <= k < n <= 104.
解释:
这系列题目的第一题:
526. Beautiful Arrangement(python+cpp)
对于本题目,就是求1-n构成的数组的一个序,这个序要满足两两之间元素差的绝对值(相同的值算一种情况)构成的数组大小为k。返回满足条件的数组序列。
尝试着去找规律,发现是很简单的一个规律题。首先我们确定的一点:元素差最多的个数是n-1
个,这个n-1
的构成也很容易发现,较大的数和较小的数交替形成的序列就满足要求。例如,我们假设n= 6,k = 5,那么这个序列就是 6 1 5 2 4 3 形成的k个元素差为: 5 4 3 2 1 (反向也是可以的 即 1 6 2 5 3 4)若k不等于n-1,我们只需要按上述规律形成满足k-1的序列,剩余序列按递减序即可(剩余的差值都为1)
假设n = 6,k = 4,我们得到的序列即是: 1 6 2 5 4 3。
所以要用双指针做。
注意,上面的循环完成以后,只有k-2个,所以最后需要先往上跳一个变成k-1个,再递减序列。上面的判断一定是left所指的数结尾。
python代码:
class Solution(object):
def constructArray(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
left=1
right=n
result=[]
while left<=right:
if k>1:
if k%2==0:
result.append(left)
left+=1
else:
result.append(right)
right-=1
k-=1
else:
result.append(right)
right-=1
return result
c++代码:
class Solution {
public:
vector<int> constructArray(int n, int k) {
int left=1,right=n;
vector<int> result;
while (left<=right)
{
if (k>1)
result.push_back((k--%2)==0?left++:right--);
else
result.push_back(right--);
}
return result;
}
};
总结:
c++代码比python代码更加简洁,恩。