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

    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:

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

    题目含义:给定整数n和k,列表[a1, a2, a3, ... , an] = [1, 2, 3, ..., n],重新排列,使得列表[|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] 恰好包含k个不同整数。

    思路:

    给定n那么k最大为n-1,假设这k个数字是 n-1,n-2,n-3...1,所以数列可以是1,n-1,2,n-2,....,

    比如给定n=9 k=8则数列可以是9 1 8 2 7 3 6 4 5,可以看出这组数据差值是8 7 6 5 4 3 2 1

    比如给定n=9 k=4则数列可以是9 1 8 2 3 7 4 6 5,可以看出这组数据差值是8 7 6 1 1 1 1 1

    1     public int[] constructArray(int n, int k) {
    2         int[] res = new int[n];
    3         int left = 1, right = n;
    4         for (int i = 0; left <= right; i++) {
    5             res[i] = k > 1 ? (k-- % 2 == 0 ? right-- : left++) : left++;  //从最大和最小数轮流取值.k为偶数时从右拿,k为奇数时候从左拿
    6         }
    7         return res;
    8     }
  • 相关阅读:
    FZU 2104 Floor problem (水题)
    POJ 1797 Heavy Transportation (最短路变形)
    ZOJ 3708 Density of Power Network (水题)
    POJ 2488 A Knight's Journey (DFS)
    HDU 1198 Farm Irrigation (并查集)
    HDU 1052 Tian Ji -- The Horse Racing (贪心)
    HDU 1598 find the most comfortable road (并查集||最短路)
    poj 2533 Longest Ordered Subsequence(最长上升子序列)
    hdu 2025 查找最大元素 (水)
    hdu 5142 NPY and FFT(水)
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7678782.html
Copyright © 2011-2022 走看看