leetcode premium,【leetcode】667. Beautiful Arrangement II

 2023-10-08 阅读 27 评论 0

摘要:題目如下: Given two integers?n?and?k, you need to construct a list which contains?ndifferent 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|

題目如下:

Given two integers?n?and?k, you need to construct a list which contains?ndifferent 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.

?

leetcode premium、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:

  1. The?n?and?k?are in the range 1 <= k < n <= 104.

解題思路:感覺自己對“給定一個條件,輸出對應排列”這一類型的題目比較沒有思路。本題的解法我也是想了很久才想出來。以[1,2,3,4,5,6]為例,當前k是等于1的;假設要k=2,只需要把6插入到頭部[6,1,2,3,4,5]即可。而如果要k=3,那么把6插入到1的后面,變成[1,6,2,3,4,5]。接下來就是遞推了,記插入6的位置為inx,要使得k=4,只要在k=2的基礎上把最后一個元素插入到inx+2的位置;同理,如果是k=5,就在k=3的基礎上操作。

代碼如下:

class Solution(object):def constructArray(self, n, k):""":type n: int:type k: int:rtype: List[int]"""res = [i for i in range(1,n+1)]inx = 0if k % 2 == 1:inx = 1else:res.insert(0, res.pop(-1))k -= 1inx += 2while k > 1:res.insert(inx,res.pop(-1))inx += 2k -= 2return res

?

leetcode hard、轉載于:https://www.cnblogs.com/seyjs/p/10090261.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/130273.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息