#68644
๐ Question ?
https://school.programmers.co.kr/learn/courses/30/lessons/68644
class Solution {
fun solution(numbers: IntArray): IntArray {
var answer: IntArray = intArrayOf()
return answer
}
}
๐งฉ Thought Process
- ์๋ฆฟ์๋ฅผ ๋ํ ๋๋ง๋ค set์ ๊ฐ์ ์ถ๊ฐํ๋ ์ฝ๋๋ฅผ ์์ฑํ๋ค. set์๋ ๊ฐ์ด ์ค๋ณต๋์ด ๋ค์ด๊ฐ์ง ์์ผ๋๊น ํจ์จ์ ์ผ ๊ฒ์ด๋ผ๊ณ ํ๋จํ๋ค.
- ์๋ ์ฝ๋ ์ฒ๋ผ ์์ฑํ๋ 44% ์ ํ๋๋ก ๋ฌธ์ ๋ฅผ ํ๋ ธ๋ค. ์๋ง๋ numbers ๋ฐฐ์ด์ ๋ฏธ๋ฆฌ ์ค๋ฆ์ฐจ์์ผ๋ก ๋ฐ๊พธ์ด ๋๊ณ ์ฐจ๊ทผ์ฐจ๊ทผ ๊ฐ์ ๋ํด์ ์ธ ๊ฒ ๊ฐ๋ค. ๊ทธ๋์ sorted์ ๋์ค์ ํด์ฃผ์๋๋ ๋ฌธ์ ๋ง์!
class Solution {
fun solution(numbers: IntArray): IntArray {
numbers.sort()
var answer = mutableSetOf<Int>()
for (i in 0 until numbers.size-1) {
for (j in i+1 until numbers.size) {
answer.add(numbers[i]+numbers[j])
}
}
return answer.toIntArray()
}
}
๐ Answer
class Solution {
fun solution(numbers: IntArray): IntArray {
var answer = mutableSetOf<Int>()
for (i in 0 until numbers.size-1) {
for (j in i+1 until numbers.size) {
answer.add(numbers[i]+numbers[j])
}
}
return answer.sorted().toIntArray()
}
}
๋ค๋ฅธ ์ฌ๋ ํ์ด #1
class Solution {
fun solution(numbers: IntArray): IntArray {
var set = mutableSetOf<Int>()
(0 until numbers.size - 1).forEach { index1 ->
(index1 + 1 until numbers.size).forEach { index2 ->
set.add(numbers[index1] + numbers[index2])
}
}
return set.sorted().toIntArray()
}
}
์ ๊ทผ ๋ฐฉ์์ ๋ด๊ฐ ํ ๋ฐฉ์๊ณผ ๋์ผํ๋ฐ for๋ฌธ ๋์ ์ forEach ๋ฅผ ์ฌ์ฉํ์๋ค. [forEach() : https://occhiolism.tistory.com/48]
๋ค๋ฅธ ์ฌ๋ ํ์ด #2
class Solution {
var answer = ArrayList<Int>()
fun solution(numbers: IntArray): IntArray {
check(numbers, Array<Boolean>(numbers.size){false}, 0, 0)
return answer.distinct().sorted().toIntArray()
}
fun check(array : IntArray, visit : Array<Boolean>, start : Int, count : Int){
var sum = 0
if(count == 2){
for(i in 0..visit.size-1){ // 5๋ฒ์งธ ์ค
if(visit[i]){
sum +=array[i]
}
} //11๋ฒ์งธ ์ค
answer.add(sum)
}
else{
for( i in start..array.size-1){
visit[i] = true
check(array, visit, i+1, count+1)
visit[i] = false
}
}
}
}
์ถ์ฒ: https://kolinuno.tistory.com/18?category=1045563 [์ฝ๋ฆฐ์ด์ ๋
ธ:ํฐ์คํ ๋ฆฌ]
์ ๊ทผ ๋ฐฉ์: ์ฌ๊ทํจ์()๋ฅผ ์ฌ์ฉํ๊ณ ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ํ์ธํ๊ธฐ ์ํด ์์ ํ์์ ํด์ฃผ์๋ค.
๐ Result
๐ Comment
sort() ํจ์๋ก ํ์ ๋๋ ์ค๋ฅ๊ฐ ๋์ ์ฝ๋๊ฐ ์๋์ด ์๋๋ค.. sorted๋ง ๋๋๊ฑธ๋ก?