프로그래머스 (등수매기기)
public class problem411 {
class Solution {
public int[] solution(int[][] score) {
int[] answer = new int[score.length];
// 평균 구하기 인데 나누지 않은 이유는
// 소수점을 구할 필요없이 더한 값만 비교하면됨으로
for (int i = 0; i < score.length; i++) {
int total = (score[i][0] + score[i][1]);
int rank = 1;
// j = 0 부터 시작하는이유는,
// 순회를 배열 처음부터 반복해야 rank가 재 할당됩니다.
for (int j = 0; j < score.length; j++) {
int compare = (score[j][0] + score[j][1]);
// 본인 배열의 값은 제외하고 검증
if (i != j) {
if (total < compare) {
rank++;
}
}
}
answer[i] = rank;
}
return answer;
}
}
}
프로그래머스 (유한소수 판별하기)
public class problem412 {
class Solution {
public int solution(int a, int b) {
int gcd = gcd(a,b);
// 분모를 최대공약수로 나눠준다.
int numB = b / gcd;
while(numB % 2 == 0){
numB /= 2;
}
while(numB % 5 == 0){
numB /= 5;
}
// numB가 1 이라는것은 나머지 없이 나눠진다는것이다.
if(numB == 1){
return 1;
}
return 2;
}
int gcd(int a, int b){
if(b == 0) return a;
return gcd(b, a % b);
}
}
}
프로그래머스 (문자열 여러 번 뒤집기)
public class problem413 {
class Solution {
public String solution(String my_string, int[][] queries) {
StringBuilder sb = new StringBuilder();
String[] mySplit = my_string.split("");
for (int[] querie : queries) {
int start = querie[0]; // 시작 인덱스
int end = querie[1]; // 마지막 인덱스
swap(mySplit, start, end);
}
for (String result : mySplit) {
sb.append(result);
}
return sb.toString();
}
// 문자열 뒤집는 메소드
void swap(String[] mySplit, int start, int end) {
while (start < end) {
String temp = mySplit[start];
mySplit[start] = mySplit[end];
mySplit[end] = temp;
start++;
end--;
}
}
}
}
프로그래머스 (무작위로 K개의 수 뽑기)
import java.util.HashSet;
import java.util.Set;
public class problem414 {
class Solution {
public int[] solution(int[] arr, int k) {
int[] answer = new int[k];
Set<Integer> num = new HashSet<>();
int count = 0;
for (int i : arr) {
// num의 set 객체의 중복을 검증한다
if (num.contains(i)) {
continue;
}
num.add(i);
answer[count] = i;
count++;
if (count >= k) {
break;
}
}
// 나머지 빈칸은 -1로 채운다.
for (int i = count; i < answer.length; i++) {
answer[i] = -1;
}
return answer;
}
}
}