<문제 2160. Minimum Sum of Four Digit Number After Splitting Digits>
[문제]
번역 :
[정확히 네 자리로 구성된 양의 정수 num이 주어집니다. num에서 찾은 자릿수를 사용하여 num을 두 개의 새 정수
new1과 new2로 나눕니다. new1과 new2에는 선행 0이 허용되며, num에서 발견되는 모든 자릿수를 사용해야 합니다.
예를 들어 num = 2932가 주어지면 2가 두 자리, 9가 한 자리, 3이 한 자리입니다. 가능한 쌍 [new1, new2] 중 일부는 [22, 93], [23, 92], [223, 9] 및 [2, 329]입니다.
new1과 new2의 가능한 최소 합을 반환합니다.]
→ 4자리의 숫자들 중 만들 수 있는 쌍 중에서, 만들 수 있는 최소합을 구하는 문제
[답안 - 1차] : 속도 0ms / 메모리 42mb
import java.util.Arrays;
class Solution {
public int minimumSum(int num) {
int[] answer = new int[4]; //4자리로 구성된 양의 정수가 주어지므로 배열값을 4로 잡아줌
for (int i = 0; i < 4 ; i++) {
answer[i] = num % 10;
num /= 10;
}
Arrays.sort(answer); // 오름차순 정렬
return(((answer[0] * 10) + answer[2])+((answer[1] * 10) + answer[3]));// (0, 2번째 인덱스 값 더하기) + (1, 3번째 인덱스 값 더하기)
}
public static void main(String args[]){
Solution sol = new Solution();
int num = 2932;
int num2 = 4009;
System.out.println(sol.minimumSum(num));
System.out.println(sol.minimumSum(num2));
}
}
→ for문을 통해 배열에 값을 나눠 담아주고, 정렬 후 값 계산을 해주어 return 시도
최소합을 구하는 규칙을 보면, 네자리 숫자에는 같은 값이 2개 나오는것처럼 보였다.
그래서 오름차순 정렬을 한뒤에, (0번째 인덱스 * 10)(십의자리) + 2번째 인덱스 와
(1번째 인덱스 * 10)(십의 자리) + 3번째 인덱스를 return 하였을 때 결과값에 문제가 없고, 제대로 통과는 한다.
다만, 속도는 0ms가 나오는 반면 Memory를 너무 많이 차지해서(...) 다른 방법을 찾아보았다.
[답안 - 최종] : 속도 0ms / 메모리 38.9mb
import java.util.Arrays;
class Solution {
public int minimumSum(int num) {
int[] answer = new int[4]; //4자리로 구성된 양의 정수가 주어지므로 배열값을 4로 잡아줌
for (int i = 0; i < 4 ; i++) {
answer[i] = num % 10;
num /= 10;
}
Arrays.sort(answer); // 오름차순 정렬
return (10 * (answer[0] + answer[1])) + answer[2] + answer[3];
}
public static void main(String args[]){
Solution sol = new Solution();
int num = 2932;
int num2 = 4009;
System.out.println(sol.minimumSum(num));
System.out.println(sol.minimumSum(num2));
}
}
→
규칙을 다시 한 번 천천히 살펴보니, 오름차순으로 정렬한 배열의 0번째와 1번째 인덱스를 더한 값에 10을 곱해주고,
거기에 2번째 , 3번째 인덱스를 더해도 값이 출력이 되는 것을 발견!
해당 식으로 풀이 시 메모리를 첫번째 방식보다 아낄 수 있었다.
출처
https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/description/
Minimum Sum of Four Digit Number After Splitting Digits - LeetCode
Minimum Sum of Four Digit Number After Splitting Digits - You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, an
leetcode.com
'알고리즘 풀이(JAVA) > leetcode' 카테고리의 다른 글
[leetcode] 1431. Kids With the Greatest Number of Candies (java) (2) | 2023.03.11 |
---|---|
[leetcode] 2574. Left and Right Sum Differences (java) (0) | 2023.02.27 |
[leetcode] 2114. Maximum Number of Words Found in Sentences (java) (0) | 2023.02.14 |
[leetcode] 2413. Smallest Even Multiple (java) (0) | 2023.02.08 |
[leetcode] 1672. Richest Customer Wealth (java) (0) | 2023.02.07 |