-
[LeetCode] 1470. Shuffle the Array c+Coding Test/LeetCode 2022. 10. 10. 16:31728x90
- 문제
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].
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].
- 문제 해결
class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { vector<int> answer; for(int i = 0; i < n; i++){ answer.push_back(nums[i]); answer.push_back(nums[i+n]); } return answer; } };
다른 방법
class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { int len = nums.size(); // to store the pair of numbers in right half of the original array for(int i = n; i < nums.size(); i++) { nums[i] = (nums[i] * 1024) + nums[i - n]; } int index = 0; // to retrive values from the pair of numbers and placing those retrieved value at their desired position for(int i = n; i < nums.size(); i++, index += 2) { nums[index] = nums[i] % 1024; nums[index + 1] = nums[i] / 1024; } return nums; } };
다른 방법2
class Solution { public: vector<int> shuffle(vector<int>& nums, int n) { int len = nums.size(); for(int i = n; i < len; i++) { nums[i] = (nums[i] << 10) | nums[i - n]; } int index = 0; for(int i = n; i < len; i++, index += 2) { nums[index] = nums[i] & 1023; nums[index + 1] = nums[i] >> 10; } return nums; } };
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 1512. Number of Good Pairs c++ (0) 2022.10.10 [LeetCode] 1672. Richest Customer Wealth c++ (0) 2022.10.10 [LeetCode] 2011. Final Value of Variable After Performing Operations c++ (0) 2022.10.10 [LeetCode] 35. Search Insert Position c++ (0) 2022.10.10 [LeetCode] 1480. Running Sum of 1d Array c++ (0) 2022.10.10