[Leetcode]1470. Shuffle the Array(O)
2024. 7. 27. 20:45ㆍjava/javaAlgorithm
1. problem :
https://leetcode.com/problems/shuffle-the-array/description/
2. solution 1 :
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] ans = new int[nums.length];
for (int i = 0; i < n; i += 1) {
ans[2*i] = nums[i];
ans[2*i +1] = nums[i+n];
}
return ans;
}
}
ans짝수번째는 nums [i]를 ans홀수번째는 nums [i+n]을 설정해 주면 된다. (은근히 헷갈림)
3. solution 2 :
class Solution {
public int[] shuffle(int[] nums, int n) {
int[] temp = new int[2*n];
int p1 = 0;
int p2 = n;
int p3 = 0;
while (p1 < n && p2 < 2*n) {
temp[p3++] = nums[p1++];
temp[p3++] = nums[p2++];
}
return temp;
}
}
3 pointer approach다. 이건 다른 사람의 solution이다. p3를 temp의 index로 설정하고, p1은 nums의 전반부 p2는 nums의 후반부의 index를 담당한다. 참으로 색다른 풀이다.
4. solution 3 :
public class ShuffleArray {
public static int[] shuffle(int[] nums, int n) {
int[] result = new int[2 * n];
int index = 0;
for (int i = 0, j = n; i < n; i++, j++) {
result[index++] = nums[i];
result[index++] = nums[j];
}
return result;
}
for문안에 int i와 int j를 동시에 설정하고 푸는 법. solution 2와 비슷하지만, 변수를 for문안에서 선언했다는 점에서 차이가 있다.
'java > javaAlgorithm' 카테고리의 다른 글
[Leetcode]654. Maximum Binary Tree (0) | 2024.07.29 |
---|---|
[Leetcode]2942. Find Words Containing Character (0) | 2024.07.28 |
[Leetcode]300. Longest Increasing Subsequence(x) (0) | 2024.07.27 |
[Leetcode]1512. Number of Good Pairs (0) | 2024.07.26 |
[Leetcode]2011. Final Value of Variable After Performing Operations (0) | 2024.07.26 |