Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ฐฐ์—ด ์ž๋ฅด๊ธฐ, ์ง์ˆ˜ ํ™€์ˆ˜ ๊ฐœ์ˆ˜

_silver 2025. 3. 5. 01:57


๋ฌธ์ œ 1.  ๋ฐฐ์—ด ์ž๋ฅด๊ธฐ
โ˜‘๏ธ ๋ฌธ์ œ ๋ฐ”๋กœ ํ’€๊ธฐ ํด๋ฆญ

 

๋‚˜์˜ ๋ฌธ์ œ ํ’€์ด
import java.util.Arrays;

class Solution {
    public int[] solution(int[] numbers, int num1, int num2) {
        
        // Arrays.copyOfRange(๋ฐฐ์—ด, start, end)๋Š” end ์ธ๋ฑ์Šค๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ num2 + 1๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ num2๊ฐ€ ํฌํ•จ ๋  ์ˆ˜ ์žˆ๋„๋ก ์„ค์ •
        return Arrays.copyOfRange(numbers, num1, num2 + 1);
        
    }
}

 

์‹คํ–‰ ๊ณผ์ • ์˜ˆ์‹œ....

numbers = {1, 2, 3, 4, 5}, num1 = 1, num2 = 3

solution.solution(new int[] {1, 2, 3, 4, 5}, 1, 3);

Arrays.copyOfRange(numbers, 1, 4);   // num + 1 = 4

๊ฒฐ๊ณผ: [2, 3, 4]

 

์ฝ”๋“œ ์„ค๋ช…

1. Arrays.copyOfRange(๋ฐฐ์—ด, start, end) ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉ

2. ๋(end) ์ธ๋ฑ์Šค๋ฅผ ํฌํ•จํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ(start ≤ index < end) num2 + 1์„ ์‚ฌ์šฉํ•˜์—ฌ num2๊ฐ€ ํฌํ•จ๋˜๋„๋ก ์„ค์ •

 


 

 

๋ฌธ์ œ 2.  ์ง์ˆ˜ ํ™€์ˆ˜ ๊ฐœ์ˆ˜
โ˜‘๏ธ ๋ฌธ์ œ ๋ฐ”๋กœ ํ’€๊ธฐ ํด๋ฆญ

 

๋‚˜์˜ ๋ฌธ์ œ ํ’€์ด
class Solution {
    public int[] solution(int[] num_list) {
        
        //0 ์ธ๋ฑ์Šค: ์ง์ˆ˜, 1 ์ธ๋ฑ์Šค: ํ™€์ˆ˜
        int[] answer = new int[2];
        
        for(int num : num_list) {
            answer[num % 2]++;
        }
        
        return answer;
    }
}

 

์ฝ”๋“œ ์„ค๋ช…

1. ์ง์ˆ˜์™€ ํ™€์ˆ˜ ๊ฐœ์ˆ˜๋ฅผ ์ €์žฅํ•  ๋ฐฐ์—ด answer ์ƒ์„ฑ

 - answer[0]์—๋Š” ์ง์ˆ˜ ๊ฐœ์ˆ˜, answer[1]์—๋Š” ํ™€์ˆ˜ ๊ฐœ์ˆ˜๋ฅผ ์ €์žฅํ•˜๋„๋ก ๋ฐฐ์—ด ์ดˆ๊ธฐํ™”

2. ํ–ฅ์ƒ๋œ for๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ๋‚˜๋จธ์ง€ ์—ฐ์ƒ ์ˆ˜ํ–‰

 - num %2 ์—ฐ์‚ฐ์„ ํ†ตํ•ด ์ˆซ์ž๊ฐ€ ์ง์ˆ˜์ธ์ง€, ํ™€์ˆ˜์ธ์ง€ ํŒ๋ณ„

 - num % 2 == 0์ด๋ฉด result[0]++ (์ง์ˆ˜ ๊ฐœ์ˆ˜ ์ฆ๊ฐ€)

- num % 2 == 1์ด๋ฉด result[1]++ (ํ™€์ˆ˜ ๊ฐœ์ˆ˜ ์ฆ๊ฐ€)

3. ์ตœ์ข…์ ์œผ๋กœ [์ง์ˆ˜ ๊ฐœ์ˆ˜, ํ™€์ˆ˜ ๊ฐœ์ˆ˜] ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜