π Algorithm
[νν΄99] μκ³ λ¦¬μ¦ λͺ¨μκ³ μ¬ - μμμ κ°μμ λ§μ
kyuu_ng
2022. 11. 23. 23:02
- λ¬Έμ :
- λ¬Έμμ΄ Sμ 곡백μΌλ‘ ꡬλΆλ μ«μλ€μ΄ μ μ₯λμ΄μλλ°, ν΄λΉ μ«μ μ€ μμμ μ΅λκ°κ³Ό μμκ° μλ μμ μ΅μκ°μ μ°Ύμ λ°ννλ λ¬Έμ
- μμλ μλ€
- μμ€μ½λ
package examPrac;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class exam3 {
public String solution(String s) {
String[] sSplit = s.split(" ");
// λ¬Έμμ΄ Sλ₯Ό λ°μμ 곡백μ κΈ°μ€μΌλ‘ μλΌμ λ°°μ΄μ μ μ₯νλ€.
// μμμ, μμκ° μλ νλͺ©λ€μ λ΄μ Listλ₯Ό μμ±νλ€.
List<Integer> sosu = new ArrayList<Integer>();
List<Integer> nososu = new ArrayList<Integer>();
int[] newArr = new int[sSplit.length];
// 곡백μ κΈ°μ€μΌλ‘ μλ₯Έ μ«μλ₯Ό λ΄κ³ μλ λ¬Έμμ΄ λ°°μ΄μ λ°μ΄ν°λ₯Ό μ μ λ°°μ΄μ λ£κΈ°μν΄ μ μν λ°°μ΄μ μμ±νλ€.
for (int i = 0; i < sSplit.length; i++) {
// sSplit ν¬κΈ°λ§νΌ λ°λ³΅νμ¬ λ°μ΄ν°λ₯Ό μ μν λ°°μ΄μ μ μ₯νλ€
newArr[i] = Integer.parseInt(sSplit[i]);
}
// μμλ₯Ό ꡬνκΈ° μν λ°λ³΅λ¬Έ
// μμλ 1κ³Ό μκΈ° μμ μΈ λ€λ₯Έ μ«μλ‘ λλμ΄μ§μ§ μλ μ«μλ‘ μ½μλ 2κ° μ΄νμ¬μΌν¨
// μ½μκ° 2κ° μ΄μμ΄λ©΄ μμκ° μλκ±Έλ‘ νλ³ νμμ
for (int i = 0; i < newArr.length; i++) {
// iλ 0λΆν° newArrμ κΈΈμ΄λ§νΌ λ°λ³΅νλ€.
int cnt = 0;
// cntλ₯Ό 첫λ²μ§Έ forλ¬Έμμ μ΄κΈ°ν νλ μ΄μ λ 2λ²μ§Έ forλ¬Έμμ newArr[i] λ§νΌ μ°μ°μ νλ©΄μ Cntλ₯Ό μ¦κ° μν¨ ν
// newArr[i]μ μ°μ°μ΄ λλκ³ newArr[i+1]μ μ°μ°μ΄ μμλμμ λ λ€μ 0 λΆν° μ΄κΈ°ννμ¬ cntλ₯Ό μΈμΌνκΈ° λλ¬Έμ
for (int j = 1; j <= newArr[i]; j++) {
// μ½μκ° 2κ°(1κ³Ό λμμ )μ΄μμΌλλ₯Ό ꡬν κ²μ΄κΈ° λλ¬Έμ Jλ 1λΆν° newArr[i]μ κ°λ§νΌ λ°λ³΅νλ€.
if (newArr[i] % j == 0) {
// newArr[i]λ₯Ό j(1~newArr[i])λ‘ λλ΄μλ λλ¨Έμ§κ° 0μ΄λ©΄ μμκ° μλλ―λ‘
cnt += 1; }
// cnt λ₯Ό 1μ© μ¦κ°νλ€.
}if (cnt >= 3) {
// λλ²μ§Έ forλ¬Έ νλ°κΎΈ λ νμ cntκ° 3 μ΄μ(=μ½μκ° 3μ΄μ)μΌ κ²½μ°
nososu.add(newArr[i]);
// nososu 리μ€νΈμ ν΄λΉ κ°μ μΆκ°νλ€.
} else {
// cntκ° 3 λ―Έλ§ (=2,1)μΌκ²½μ° μμμ΄κΈ° λλ¬Έμ
sosu.add(newArr[i]);
// sosu λ°°μ΄μ μΆκ°νλ€.
}
}
int max = Collections.max(sosu);
// Collections.max ν¨μλ₯Ό μ΄μ©ν΄μ sosu 리μ€νΈμ μ΅λκ°μ ꡬνλ€.
int min = Collections.min(nososu);
// Collections.min ν¨μλ₯Ό μ΄μ©ν΄μ nososu 리μ€νΈμ μ΅μκ°μ ꡬνλ€.
String total = "μ΅μ : " + min + "μ΅λ : " + max;
return total;
}
public static void main(String[] args) {
// String s = "2 3 4 5";
String s = "15 3 10 9 7 8";
exam3 exam = new exam3();
System.out.println(exam.solution("2 3 4 5"));
System.out.println(exam.solution( "15 3 10 9 7 8"));
System.out.println(exam.solution( "97 75 88 99 95 92 73"));
}
}
- νμ΄ :
- μ΄ λ¬Έμ λ₯Ό νκΈ° μν΄μλ μμκ° λμ§ λΆν° μμμΌνλ€.
π μμλ λλ΄μλ 1κ³Ό λ΄ μμ μΌλ‘λ§ λλμ΄μ§λ μ = μ¦ μ½μκ° 2κ°μΈ μ μ΄λ€. - λλ λ¬Έμ μμ μ½μκ° 2κ° μ΄νμΈ μλ₯Ό μμλ‘ νλ¨νκ²λ μμ€μ½λλ₯Ό μμ±νμλ€.
γ΄ μ½μ κ°―μλ₯Ό μΈκΈ°μν΄ cntλΌλ λ³μλ₯Ό, μμ/μμκ° μλ μ μ 리μ€νΈλ₯Ό λ§λ€μ΄μ λΆλ₯νμ¬ λͺ¨μλ€μ μ΅μ/μ΅λκ°μ ꡬνλ€.