개발의변화
LeetCode 321. Create Maximum Number 본문
반응형
https://leetcode.com/problems/create-maximum-number/
스택을 활용한 그리디 문제였다.
배열의 0부터 해당 인덱스까지에서 최대 수를 구하는 것으로 생각해야 하는 부분들이 많았다.
public static int [] findMaxArray(int length, int [] nums) {
int maxPop = nums.length - length;
Stack <Integer> s = new Stack<>();
int [] result = new int [length];
for (int i = 0; i < nums.length; i++) {
while(maxPop > 0 && !s.isEmpty() && s.peek() < nums[i]) {
s.pop();
maxPop--;
}
s.add(nums[i]);
}
while(s.size() > length) s.pop();
for (int i =length - 1; i >= 0; i--) {
result[i] = s.pop();
}
return result;
}
- 순회하면서 스택의 값과 비교하여 큰 값이 나오면 스택의 값을 뺀다.
1-A 하지만 배열의 길이에서 뽑아내야하는 요소의 길이가 제한되어있으므로 스택의 pop할 횟수를 제어해주는 것이 포인트였다.
즉 최대로 pop할 수 있는 횟수는 배열의 길이에서 뽑아내야할 요소의 길이이므로 최대횟수를 넘어가면 그때부터는 1번 순서를 넘어 어가야 했다.
public static int [] mergeArray(int [] nums1, int [] nums2 ) {
ArrayList <Integer> a = new ArrayList<>();
int s1 = 0;
int s2 = 0;
while(s1 < nums1.length || s2 < nums2.length) {
if (s1 >= nums1.length) {
while(s2 < nums2.length) {
a.add(nums2[s2++]);
}
}
else if (s2 >= nums2.length) {
while(s1 < nums1.length) {
a.add(nums1[s1++]);
}
}
else {
int n1 = nums1[s1];
int n2 = nums2[s2];
if (check(Arrays.copyOfRange(nums1, s1, nums1.length), Arrays.copyOfRange(nums2, s2, nums2.length))) {
a.add(nums1[s1++]);
}
else {
a.add(nums2[s2++]);
}
}
}
return a.stream().mapToInt(i -> i).toArray();
}
- 그 이후 두 배열에서 값을 비교할 때 비교의 조건절은 배열 순서대로 탐색하면서 큰 값을 비교하고 만약 두 배열을 비교할 때 최소길이와 최대길이가 다를 땐 배열의 길이가 긴 녀석을 우선적으로 탐색해야 했다.
public static boolean check(int [] s1 , int [] s2) {
for (int i = 0; i < Math.min(s1.length,s2.length); i++) {
if (s1[i] > s2[i]) return true;
else if (s1[i] < s2[i]) return false;
}
if (s1.length > s2.length) return true;
else if(s2.length > s1.length) return false;
return true;
}
반응형
'알고리즘' 카테고리의 다른 글
Leetcode 1964. Find the Longest Valid Obstacle Course at Each Position (0) | 2024.04.08 |
---|---|
LeetCode: 3Sum Closest (1) | 2024.03.29 |
LeetCode 1220. Count Vowels Permutation (0) | 2024.03.28 |
LeetCode: Maximum Value of K Coins From Piles (0) | 2024.03.27 |
프로그래머스 LV3 다단계 칫솔판매 (2) | 2024.03.19 |