667. Beautiful Arrangement II
来源:互联网 发布:软考数据库工程师 编辑:程序博客网 时间:2024/05/16 03:21
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 = 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.
* 注意到:1..n最多可以弄出n-1个不同的差,比如1..9就是
* 192837465
* diff: 8 7 6 5 4 3 2 1
假设要n=9 k=6 那么产生1 9 2 8 3 7 6 5 4 先产生k个数,也就是k-1个差值,然后剩下的n-k个数就需要按照差值为1进行产出,但是要特别提示的是,最后这几个数的产生是依赖于第k个数的位置,因为这这个数组中有两串,一个顺序,一个逆序,所以这里需要判断一下,再进行循环。
public static int[] constructArray(int n, int k) { int []res=new int[n]; int l=1,r=n,i=0; for(;i<k;i++){//先产生k个数 if(i%2==0) res[i]=l++; else res[i]=r--; } //将剩余的n-k个数放到数组中 if(i%2==1){//因为此时缺位为奇数位,但是前一位为偶数位,要达到差值为1,此时要自然序数递增产生余下的数 for(int j=k;j<n;j++) res[j]=l++; }else {//因为此时缺位为偶数数位,但是前一位为奇数位,要达到差值为1,此时要r--for(int j=k;j<n;j++) res[j]=r--;} return res; }
阅读全文
1 0
- 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II。
- 667. Beautiful Arrangement II
- LeetCode 667. Beautiful Arrangement II
- leetcode 667. Beautiful Arrangement II
- LeetCode 667. Beautiful Arrangement II
- LeetCode 667. Beautiful Arrangement II
- leetcode 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II(Java)
- LeetCode 667. Beautiful Arrangement II
- leetcode 667. Beautiful Arrangement II
- 667. Beautiful Arrangement II 找规律
- leetcode- Beautiful Arrangement II
- leetCode-Beautiful Arrangement II
- leetcode 667. Beautiful Arrangement II 双指针遍历
- Jq表单智能校验(Jq查找和事件处理)
- java---InputStream
- 亚马逊要做一款会说话的智能眼镜,但看起来没那么性感
- 互联网商业变现与计算广告(干货+5000字精彩问答)
- Hello Struts2
- 667. Beautiful Arrangement II
- 分页插件PageHelper
- listView加载
- Volley的框架解读七(Request)
- 深入浅出WPF之我见7
- UTC时间字符串转换为本地时间(北京)
- Tablayout+fragment
- EasyJoyStick使用以及两种操作杆 EasyJoyStick的使用方法,简单的不能再简单 Hedgehog Team-》Easy Touch -》Add Easy Touch For C#
- Linux驱动开发调试 -- 打开dev_dbg()