TIL 24.02.13

ν™©μ€ν•˜Β·2024λ…„ 2μ›” 13일
0

TIL

λͺ©λ‘ 보기
145/146

πŸ“ŒToday I Learned

ν˜•λ³€ν™˜

κ·Έλ™μ•ˆ 1일 1μ½”λ”©κ³Ό μ£Ό 2νšŒμ”© μ½”λ”©ν…ŒμŠ€νŠΈ μŠ€ν„°λ””λ₯Ό μ§„ν–‰ν•˜μ˜€λŠ”λ°, λΈ”λ‘œκ·Έ μž‘μ„±μ΄ μ μ—ˆλ‹€. λ‹€μ‹œ κ³΅λΆ€ν•œ λ‚΄μš©μ„ μ •λ¦¬ν•˜λŠ” μ‹œκ°„μ„ 자주 κ°€μ Έμ•Όκ² λ‹€.

ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ - μ΅œλŒ“κ°’κ³Ό μ΅œμ†Ÿκ°’

문제λ₯Ό ν‘ΈλŠ”λ° String 배열을 int λ°°μ—΄λ‘œ λ°”κΎΈλŠ”λ° λ¬Έμ œκ°€ μžˆμ—ˆλ‹€.

import java.util.*;

class Solution {
    public String solution(String s) {
    
        String[] arr = s.split(" ");
        
        int[] intArr = Arrays.stream(arr).mapToInt(i -> i).toArray();
        
        Arrays.sort(intArr);
        
        return intArr[0] + " " + intArr[intArr.length - 1];
    }
}

mapToInt()μ—μ„œ i -> i둜 μž‘μ„±ν–ˆλ”λ‹ˆ,

/Solution.java:6: error: incompatible types: bad return type in lambda expression
int[] intArr = Arrays.stream(arr).mapToInt(i -> i).toArray();
^
String cannot be converted to int

λΌλŠ” 였λ₯˜κ°€ λ°œμƒν•˜μ˜€λ‹€. 이 였λ₯˜λŠ” Stringν˜•μ„ λ°”λ‘œ intν˜•μœΌλ‘œ λ³€κ²½ν•  수 μ—†μ–΄μ„œ λ°œμƒν•˜λŠ” 것이닀. 이전에 mapToInt()λ₯Ό 보톡 Integer λ¦¬μŠ€νŠΈμ—μ„œ int λ°°μ—΄λ‘œ λ³€κ²½ν•  λ•Œ μ‚¬μš©ν•˜λ˜ λ©”μ†Œλ“œμ˜€κΈ°μ— 별닀λ₯Έ 생각 없이 μŠ΅κ΄€λŒ€λ‘œ μ‚¬μš©ν•˜μ—¬ λ¬Έμ œκ°€ λ°œμƒν–ˆλ‹€.

λžŒλ‹€ ν‘œν˜„μ‹μ˜ λ§€κ°œλ³€μˆ˜ Integerμ—μ„œ intλŠ” μ»΄νŒŒμΌλŸ¬κ°€ 좔둠이 κ°€λŠ₯ν•˜μ—¬ μ•”μ‹œμ μœΌλ‘œ λ³€ν™˜μ΄ κ°€λŠ₯ν•˜μ§€λ§Œ, Stringμ—μ„œ intλŠ” λͺ…μ‹œμ μœΌλ‘œ μž‘μ„±ν•΄μ•Ό λ³€ν™˜μ΄ λœλ‹€. κ·Έλž˜μ„œ Integer::parseInt둜 λͺ…μ‹œμ μœΌλ‘œ μž‘μ„±ν•˜μ—¬ Stringμ—μ„œ int둜 λ³€ν™˜ν•˜μ˜€λ‹€.

μ•„λž˜λŠ” μˆ˜μ •λœ μ½”λ“œλ‹€.

import java.util.*;

class Solution {
    public String solution(String s) {
    
        String[] arr = s.split(" ");
        
        int[] intArr = Arrays.stream(arr).mapToInt(Integer::parseInt).toArray();
        
        Arrays.sort(intArr);
        
        return intArr[0] + " " + intArr[intArr.length - 1];
    }
}

μ •μƒμ μœΌλ‘œ μ½”λ“œκ°€ μˆ˜ν–‰λ˜μ—ˆλ‹€.

μ•žμœΌλ‘œλŠ” μŠ΅κ΄€λŒ€λ‘œ ν•˜μ§€ μ•Šκ³ , μ½”λ“œλ₯Ό 읽고 λ§€κ°œλ³€μˆ˜λ‚˜ μž‘μ„±λ²•μ„ 더 μƒκ°ν•˜κ³  μž‘μ„±ν•΄μ•Όκ² λ‹€.

profile
μ°¨κ·Όμ°¨κ·Ό ν•˜λ‚˜μ”©

0개의 λŒ“κΈ€