반응형
https://leetcode.com/problems/shuffle-the-array/description/
Shuffle the Array - LeetCode
Shuffle the Array - Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. Example 1: Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2
leetcode.com
간단 구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
정답 변수 vector ans를 선언합니다.
📔 풀이과정
2n개의 원소가 nums에 있으므로 무조건 짝수개의 원소가 존재합니다.
nums.size() / 2만큼 for loop를 수행합니다. i와 i + sz/2 번째의 원소를 ans에 저장해줍니다.
📔 정답반환
ans를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
vector <int> ans;
int sz = nums.size();
for(int i = 0; i < sz / 2; i++) {
ans.push_back(nums[i]);
ans.push_back(nums[i + sz / 2]);
}
return ans;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 326. Power of Three (0) | 2023.02.13 |
---|---|
(C++) - LeetCode (easy) 292. Nim Game (0) | 2023.02.08 |
(C++) - LeetCode (easy) 283. Move Zeroes (0) | 2023.02.03 |
(C++) - LeetCode (easy) 258. Add Digits (0) | 2023.01.25 |
(C++) - LeetCode (easy) 242. Valid Anagram (0) | 2023.01.20 |