博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】667. Beautiful Arrangement II
阅读量:6991 次
发布时间:2019-06-27

本文共 1517 字,大约阅读时间需要 5 分钟。

题目如下:

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 = 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:

  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 = 0        if k % 2 == 1:            inx = 1        else:            res.insert(0, res.pop(-1))            k -= 1            inx += 2        while k > 1:            res.insert(inx,res.pop(-1))            inx += 2            k -= 2        return res

 

转载于:https://www.cnblogs.com/seyjs/p/10090261.html

你可能感兴趣的文章
uva 1395(kruskal变形)
查看>>
斜率优化
查看>>
php 比较运算符
查看>>
for循环效率问题求解答
查看>>
Android so lib库远程http下载和动态注册
查看>>
痞子衡嵌入式:并行接口NAND标准(ONFI)及SLC Raw NAND简介
查看>>
Q-criterion- definition and post-processing
查看>>
单例模式-Singleton
查看>>
OneZero第二周第二次站立会议(2016.3.29)
查看>>
(转)移动开发:Ant自动化打包APK(1)--ANT,Android 环境配置与打包
查看>>
eclipse怎么删除多余的tomcat server(2)
查看>>
python面试题
查看>>
Day10 - Ruby如何调用方法(invoke method)?
查看>>
java中的异常
查看>>
mysql查询重复数据
查看>>
Tesseract 引擎翻译
查看>>
Android之复选框对话框
查看>>
【RabbitMQ系列】队列、绑定、交换器
查看>>
Run as ant build每次都执行两次
查看>>
如何在微信公众号下载保存图片??
查看>>