๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค[Java] - (Level2)ํƒ‘

by ์ฃผ๋ฐœ2 2020. 3. 16.
๋ฐ˜์‘ํ˜•

https://programmers.co.kr/learn/courses/30/lessons/42588

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

์ฝ”๋“œ

class Solution {
	public static int[] solution(int[] heights) {
		int[] answer = new int[heights.length];
		answer[0] = 0;
		for(int i=heights.length-1; i>0; i--) {
			for(int j=i-1; j>=0; j--) {
				if(heights[i] < heights[j]) {
					answer[i] = j+1;
					break;
				}
			}
		}
		return answer;
	}
}

ํ’€์ด

๋ฌธ์ œ์˜ ์˜ˆ์ œ์ฒ˜๋Ÿผ ํƒ‘์˜ ๋†’์ด๊ฐ€ heights = [6, 9, 5, 7, 4] ๋ฅผ ๊ทธ๋ฆผ์œผ๋กœ ํ‘œ์‹œํ•˜๋ฉด ์œ„์™€ ๊ฐ™๋‹ค.

์˜ค๋ฅธ์ชฝ(4)๋ถ€ํ„ฐ ๊ฐ ํƒ‘์ด ์‹ ํ˜ธ๋ฅผ ์˜๋ฉด, ๊ทธ ํƒ‘๋ณด๋‹ค ๋†’์€ ํƒ‘์ด ์‹ ํ˜ธ๋ฅผ ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ํƒ‘(๋†’์ด=4)๊ฐ€ ์‹ ํ˜ธ๋ฅผ ๋ฐœ์‚ฌํ•˜๋ฉด, ๋ฐ”๋กœ ์™ผ์ชฝ์— ์žˆ๋Š” ๋„ค ๋ฒˆ์งธ ํƒ‘์ด ์‹ ํ˜ธ๋ฅผ ๋ฐ›๊ณ ,

๋„ค ๋ฒˆ์งธ ํƒ‘(๋†’์ด=7)์ด ์‹ ํ˜ธ๋ฅผ ๋ณด๋‚ด๋ฉด ๋‘ ๋ฒˆ์งธ ํƒ‘(๋†’์ด=9)์ธ ํƒ‘์ด ์‹ ํ˜ธ๋ฅผ ๋ฐ›๊ณ ,

์„ธ ๋ฒˆ์งธ ํƒ‘(๋†’์ด=5)์ด ์‹ ํ˜ธ๋ฅผ ๋ณด๋‚ด๋ฉด ๋‘ ๋ฒˆ์งธ ํƒ‘(๋†’์ด=9)์ธ ํƒ‘์ด ์‹ ํ˜ธ๋ฅผ ๋ฐ›๊ณ ,

๋‘ ๋ฒˆ์งธ ํƒ‘(๋†’์ด=9)์€ ์ขŒ์ธก์— ์ž์‹ ๋ณด๋‹ค ๋†’์€ ํƒ‘์ด ์—†์œผ๋ฏ€๋กœ ์‹ ํ˜ธ๋ฅผ ๋ฐ›์ง€ ๋ชปํ•˜๊ณ ,

์ฒซ ๋ฒˆ์งธ ํƒ‘(๋†’์ด=6)์€ ์ฒซ๋ฒˆ์งธ์ด๋ฏ€๋กœ ํ•ญ์ƒ ์‹ ํ˜ธ๋ฅผ ๋ฐ›์ง€ ๋ชปํ•œ๋‹ค.

 

i.e) ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝํƒ‘๋ถ€ํ„ฐ(i = heights.length-1) ์‹œ์ž‘ํ•ด์„œ ํƒ‘์˜ ์ฒซ๋ฒˆ์งธ๊นŒ์ง€ ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ฉด์„œ(j = i-1; j>=0)

์ž์‹ ๋ณด๋‹ค ๋†’์€ ํƒ‘์ด ์žˆ์„๊ฒฝ์šฐ(heights[i] < heights[j]

๋†’์€ ํƒ‘์˜ ์œ„์น˜(j+1)๋ฅผ returnํ•˜๋Š” ๋ฐฐ์—ด์— ๋„ฃ์–ด์ฃผ๊ณ  ๊ทธ ์ดํ›„๋Š” ํƒ์ƒ‰ํ•  ํ•„์š”๊ฐ€ ์—†์œผ๋ฏ€๋กœ break๋กœ ํƒˆ์ถœํ•œ๋‹ค.

์ฒซ ๋ฒˆ์งธ ํƒ‘์˜๊ฒฝ์šฐ ์ขŒ์ธก์— ์•„๋ฌด๋Ÿฐ ํƒ‘๋„ ์—†์œผ๋ฏ€๋กœ ํ•ญ์ƒ 0์ด๋‹ค.

 

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€