日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

667. Beautiful Arrangement II

發布時間:2023/11/30 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 667. Beautiful Arrangement II 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

找規律?

1,2,... , n 亂序排列,相鄰數據的絕對差最多有n-1種

比如1,2,3,4,5對應于 1 5 2 4 3

class Solution { public:vector<int> constructArray(int n, int k) {vector<int> res;int l=1,r=k+1;while(l<=r){res.push_back(l++);if(l<=r){res.push_back(r--);}}for(int i=k+2;i<=n;++i){res.push_back(i);}return res;} };

python代碼

class Solution(object):def constructArray(self, n, k):""":type n: int:type k: int:rtype: List[int]"""res=[]l,r=1,k+1while l<=r:res.append(l)l+=1if l<=r:res.append(r)r-=1for i in xrange(k+2,n+1):res.append(i)return res

python 代碼

class Solution(object):def constructArray(self, n, k):""":type n: int:type k: int:rtype: List[int]"""res=range(1,n-k)for i in range(0,k+1):if i%2==0:#print "{} is even".format(i)res.append(n-k+i//2)else:#print "{} is odd".format(i)res.append(n-i//2)return res;

答案

Approach #2: Construction [Accepted]

Intuition

When?k?=?n-1, a valid construction is?[1,?n,?2,?n-1,?3,?n-2,?....]. One way to see this is, we need to have a difference of?n-1, which means we need?1?and?n?adjacent; then, we need a difference of?n-2, etc.

Also, when?k?=?1, a valid construction is?[1,?2,?3,?...,?n]. So we have a construction when?n-k?is tiny, and when it is large. This leads to the idea that we can stitch together these two constructions: we can put?[1,?2,?...,?n-k-1]?first so that?n?is effectively?k+1, and then finish the construction with the first?"k?=?n-1"method.

For example, when?n?=?6?and?k?=?3, we will construct the array as?[1,?2,?3,?6,?4,?5]. This consists of two parts: a construction of?[1,?2]?and a construction of?[1,?4,?2,?3]?where every element had?2?added to it (i.e.?[3,?6,?4,?5]).

Algorithm

As before, write?[1,?2,?...,?n-k-1]?first. The remaining?k+1?elements to be written are?[n-k,?n-k+1,?...,?n], and we'll write them in alternating head and tail order.

When we are writing the?ithi?th???element from the remaining?k+1, every even?ii?is going to be chosen from the head, and will have value?n-k?+?i//2. Every odd?ii?is going to be chosen from the tail, and will have value?n?-?i//2.

class Solution(object):def constructArray(self, n, k):ans = list(range(1, n - k))for i in range(k+1):if i % 2 == 0:ans.append(n-k + i//2)else:ans.append(n - i//2)return ans

?

轉載于:https://www.cnblogs.com/learning-c/p/9266391.html

總結

以上是生活随笔為你收集整理的667. Beautiful Arrangement II的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。