Contents

์ •์ˆ˜ ์ฐพ๊ธฐ(with.Java)

   Nov 26, 2023     1 min read

โ€œ์ •์ˆ˜ ์ฐพ๊ธฐโ€ ๋ฌธ์ œ์— ๋Œ€ํ•˜์—ฌ ์•Œ์•„๋ณธ ๊ธ€์ž…๋‹ˆ๋‹ค.

์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉฐ, ํ’€์—ˆ๋˜ ๋ฌธ์ œ์— ๋Œ€ํ•œ ํšŒ๊ณ ์™€ ๋‹ค๋ฅธ ํ’€์ด ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด๋ฉฐ, ์•Œ์•„๊ฐ€๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค.

๋ฌธ์ œ์— ๋Œ€ํ•ด ๋จผ์ € ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

๋ฌธ์ œ

์ •์ˆ˜ ๋ฆฌ์ŠคํŠธ num_list์™€ ์ฐพ์œผ๋ ค๋Š” ์ •์ˆ˜ n์ด ์ฃผ์–ด์งˆ ๋•Œ, num_list์•ˆ์— n์ด ์žˆ์œผ๋ฉด 1์„ ์—†์œผ๋ฉด 0์„ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

num_listnresult
[1, 2, 3, 4, 5]31
[15, 98, 23, 2, 15]200

๋ฌธ์ œ์— ๋Œ€ํ•œ ๋‚˜์˜ ํ’€์ด

class Solution {
    public int solution(int[] num_list, int n) {
        int answer = 0;
        for(int temp: num_list){
            if(temp == n){
                answer = 1;
            }
        }
        return answer;
    }
}

ํ’€์ด ์„ค๋ช…

int answer = 0;: ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•  ์ •์ˆ˜ํ˜• ๋ณ€์ˆ˜ answer๋ฅผ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค. ์ดˆ๊ธฐ๊ฐ’์€ 0์ž…๋‹ˆ๋‹ค.

for(int temp : num_list) : ์ •์ˆ˜ ๋ฐฐ์—ด num_list๋ฅผ ๋ฐ˜๋ณตํ•˜๋ฉด์„œ ๊ฐ ์š”์†Œ temp๋ฅผ ๊ฒ€์‚ฌํ•ฉ๋‹ˆ๋‹ค.

if(temp == n) : ํ˜„์žฌ ์š”์†Œ temp๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์€ n๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ:

answer๋ฅผ 1๋กœ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

return answer;: ํŒ๋‹จ ๊ฒฐ๊ณผ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” answer ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.