Re: [閒聊] 每日LeetCode已回收
※ 引述《Rushia》之銘言
: 1470. Shuffle the Array
: 給你一個陣列和一個數字n,陣列有2n個元素,若陣列為:[x1,x2,...,xn,y1,y2,...,yn]
: ,返回如右形式的陣列:[x1,y1,x2,y2,...,xn,yn]。
: Example:
: Input: nums = [2,5,1,3,4,7], n = 3
: Output: [2,3,5,4,1,7]
: Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is
: [2,3,5,4,1,7].
: Input: nums = [1,2,3,4,4,3,2,1], n = 4
: Output: [1,4,2,3,3,2,4,1]
: 思路:
: 1.按照題目的要求把元素一個一個放進陣列就好
: JavaCode:
: ------------------------------------------
: class Solution {
: public int[] shuffle(int[] nums, int n) {
: int[] res = new int[nums.length];
: int idx = 0;
: for (int i = 0; i < n; i++) {
: for (int j = i; j < nums.length; j += n) {
: res[idx++] = nums[j];
: }
: }
: return res;
: }
: }
: ------------------------------------------
: --
: https://i.imgur.com/tdaniED.jpg

把題目給的建兩個小的vector
前半跟後半
然後迴圈一次一次在要回傳的ans 放入前半一個後半一個
class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
vector<int> ans(2*n);
vector<int> f_half(nums.begin(), nums.begin() + n);
vector<int> s_half(nums.begin()+n, nums.end());
for (int i = 0, j = 0; i < 2*n; i+=2, j++){
ans[i] = f_half[j];
ans[i+1] = s_half[j];
}
return ans;
}
};
----
Sent from BePTT
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.174.86.107 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1675668950.A.043.html
討論串 (同標題文章)
完整討論串 (本文為第 220 之 719 篇):