zoukankan      html  css  js  c++  java
  • 【leetcode】667. Beautiful Arrangement II

    题目如下:

    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.
    

    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 = 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
  • 相关阅读:
    ABAP中的‘多线程’
    SAP数据库表维护视图分配事务代码
    SAP调用外部数据库
    ABAP-小技巧/知识(1)
    sap中用函数增加断点(break point)
    把内表 itab1 的 n1 到 n2 行内容附加到 itab2 内表中去.
    ABAP打开TCODE
    查看用户下有那些事务码
    check、continue、exit的区别
    将excel数据导入内表的函数
  • 原文地址:https://www.cnblogs.com/seyjs/p/10090261.html
Copyright © 2011-2022 走看看