667. Beautiful Arrangement II(python+cpp)

题目:

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 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代码更加简洁,恩。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值