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.

 * 注意到:1..n最多可以弄出n-1个不同的差,比如1..9就是
 *
1 9 2 8 3 7 4 6 5
 * 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值