 # [코딩문제풀기 1일차] Peak Index in a Mountain Array ## Introduction - 꾸준히 코딩문제를 풀기 위해서 스팀잇에 매일매일 푼 문제의 해설을 적어보려합니다. - leetcode와 codewars 사이트를 주로 사용할 것입니다. > Talk is cheap. Show me the code. - 리누스 토발즈 ## Problem 난이도: Easy 다음 속성을 따르는 `A`라는 산 배열이 있다: - `A.length >= 3` - `A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]`를 만족하는 `0 < i < A.length - 1`가 존재한다. 산 배열이 주어지면, `A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]`를 만족하는 `i`를 반환해야 한다. **예제 1:** ``` Input: [0,1,0] Output: 1 ``` **예제 2:** ``` Input: [0,2,1,0] Output: 1 ``` **유의사항:** 1. `3 <= A.length <= 10000` 2. `0 <= A[i] <= 10^6` 3. `A`는 위에서 말했듯이 산이다. 문제 출처: [leetcode 852. Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/description/) ## Solution * Javascript를 사용해서 두 방법으로 풀었습니다. * 해설로 나온 나머지 두 방법도 설명드리겠습니다. * [Github solution 코드 보기](https://github.com/JonJee/leetcode/blob/master/js/852PeakIndexinaMountainArray.js) ### Solution 1 : `forEach`를 사용한 기본적인 방법 ```javascript let peakIndexInMountainArray = A => { let peak = -1, index = -1; A.forEach((v, i) => { if (v > peak) { peak = v; index = i; } }); return index; }; ``` * `A` 배열에서 `forEach`를 돌려서 최대값(`peak`)을 찾은 후, `index`에 그 최대값의 인덱스를 저장하고 있습니다. * 시간복잡도는 *O(N)* 으로 *N*은 `A` 배열의 길이입니다. ### Solution 2 : `Array.indexOf()`와 `Math.max()`를 사용한 방법 (Very Simple!) ```javascript let peakIndexInMountainArray = A => A.indexOf(Math.max(...A)); ``` * `A` 배열에서 최대값을 구한 후, Javascript에 내장된 `indexOf` 함수를 사용해서 최대값의 인덱스를 가져오고 있습니다. * 시간복잡도는 마찬가지로 *O(N)* 입니다. // 여기서부터는 사이트에 나와있는 해설입니다. ### Solution 3 : Linear Scan ```javascript let peakIndexInMountainArray = A => { let i = 0; while(A[i] < A[i + 1]) i++; return i; } ``` * `i`를 증가시키면서 증가하는 구간에서 감소하는 구간으로 바뀌는 순간에 반복문을 탈출하여 i를 반환합니다. * 시간복잡도는 마찬가지로 *O(N)* 입니다. ### Solution 4 : Binary Search (Very Important!!!) ```javascript let peakIndexInMountainArray = A => { let lo = 0, hi = A.length - 1 while (lo < hi) { let mi = Math.floor((lo + hi) / 2) if (A[mi] < A[mi + 1]) lo = mi + 1 else hi = mi } return lo } ``` * `A` 배열은 `A[i] < A[i+1]`이므로 `[true, true, true, ..., true, false, false, ..., false]`와 같이 나타낼 수 있습니다. (`true`가 1개 이상이고, `false`가 1개 이상입니다.) * 위 성질을 이용해서 `false`인 부분을 이진검색으로 찾을 수 있습니다. * 따라서 시간복잡도는 *O(logN)* 으로 위 3개의 solution보다 시간복잡도가 짧습니다. > 2018/06/19 Written by Jon Jee ----------
author | holykw |
---|---|
permlink | 1-peak-index-in-a-mountain-array |
category | coding |
json_metadata | {"tags":["kr-dev","coding","jjangjjangman","kr","crypto"],"image":["https://cdn.steemitimages.com/DQmbwuk85jhorPvZoCb13F7gouFg5JH9gKPBWe4H5ecthQT/holykiwi_big.png"],"links":["https://leetcode.com/problems/peak-index-in-a-mountain-array/description/","https://github.com/JonJee/leetcode/blob/master/js/852PeakIndexinaMountainArray.js"],"app":"steemit/0.1","format":"markdown"} |
created | 2018-06-19 16:44:42 |
last_update | 2018-06-19 17:38:42 |
depth | 0 |
children | 4 |
last_payout | 2018-06-26 16:44:42 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 0.184 HBD |
curator_payout_value | 0.051 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 2,576 |
author_reputation | 37,130,919,971 |
root_title | "[코딩문제풀기 1일차] Peak Index in a Mountain Array" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 61,382,097 |
net_rshares | 113,161,070,524 |
author_curate_reward | "" |
voter | weight | wgt% | rshares | pct | time |
---|---|---|---|---|---|
virus707 | 0 | 102,258,417,489 | 1% | ||
steemit-2018 | 0 | 429,708,401 | 100% | ||
mishana | 0 | 6,433,801,200 | 50% | ||
curl-j | 0 | 3,386,689,761 | 100% | ||
frontalnh | 0 | 51,901,073 | 10% | ||
secure-kor | 0 | 600,552,600 | 100% |
Get a free Bible for your phone, tablet, and computer. [bible.com](http://bible.com)
author | bible.com |
---|---|
permlink | re-holykw-1-peak-index-in-a-mountain-array-20180619t164457366z |
category | coding |
json_metadata | {"tags":["coding"],"links":["http://bible.com"],"app":"steemit/0.1"} |
created | 2018-06-19 16:44:54 |
last_update | 2018-06-19 16:44:54 |
depth | 1 |
children | 0 |
last_payout | 2018-06-26 16:44:54 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 0.000 HBD |
curator_payout_value | 0.000 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 84 |
author_reputation | -3,064,160,201,856 |
root_title | "[코딩문제풀기 1일차] Peak Index in a Mountain Array" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 61,382,115 |
net_rshares | -52,338,500,168 |
author_curate_reward | "" |
voter | weight | wgt% | rshares | pct | time |
---|---|---|---|---|---|
mack-bot | 0 | -52,338,500,168 | -0.03% |
자바스크립트도 이런코드를 쓸 수 있네요! 생각보다(?) 깊은 언어같기도... 클러이언트단에서 내려받아서 동작하는 언어라 웹해킹 취약포인트가 발생되는 부분이 참 많았던거 같아요. 스크립트 난독화 이런거만보다가 공부하는 글도 새롭네요 +.+ 아! 그리고 저도 뉴비지만...? 전체적으로 게시글들이 태그활용이 잘 안되는거같아요. 먹거리는 muksteem kr-food tasteem 태그가 있고 kr-newbie jjangjjangman 태그도 있답니다. ourselves도 있고.. 찾아보면 많다능! kr-dev 도 있을텐뎅. 현재 지갑에 스달이 $5.943 있으신거 같은데 이것도 놀지말고 보팅봇 부르시길 추천드려요! 보상이 있어야 글쓰는 재미도 있으니까요 @_@! 또 올려주세요~
author | secure-kor |
---|---|
permlink | re-holykw-1-peak-index-in-a-mountain-array-20180619t165538359z |
category | coding |
json_metadata | {"tags":["coding"],"app":"steemit/0.1"} |
created | 2018-06-19 16:55:39 |
last_update | 2018-06-19 17:10:21 |
depth | 1 |
children | 1 |
last_payout | 2018-06-26 16:55:39 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 0.000 HBD |
curator_payout_value | 0.000 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 383 |
author_reputation | 235,776,111,322 |
root_title | "[코딩문제풀기 1일차] Peak Index in a Mountain Array" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 61,383,300 |
net_rshares | 610,390,398 |
author_curate_reward | "" |
voter | weight | wgt% | rshares | pct | time |
---|---|---|---|---|---|
holykw | 0 | 610,390,398 | 100% |
긴 댓글과 팁 무진장 감사합니다!! 활성화된 태그 좀 찾아보고 보팅봇도 좀 알아봐야겠네요 감사합니다!
author | holykw |
---|---|
permlink | re-secure-kor-re-holykw-1-peak-index-in-a-mountain-array-20180619t172029540z |
category | coding |
json_metadata | {"tags":["coding"],"app":"steemit/0.1"} |
created | 2018-06-19 17:20:30 |
last_update | 2018-06-19 17:20:30 |
depth | 2 |
children | 0 |
last_payout | 2018-06-26 17:20:30 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 0.000 HBD |
curator_payout_value | 0.000 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 56 |
author_reputation | 37,130,919,971 |
root_title | "[코딩문제풀기 1일차] Peak Index in a Mountain Array" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 61,386,008 |
net_rshares | 0 |
author | virus707 | ||||||
---|---|---|---|---|---|---|---|
permlink | re-holykw-1-peak-index-in-a-mountain-array-1529565302951tab95a3de-e87b-46be-a465-f46b139bfbaauid | ||||||
category | coding | ||||||
json_metadata | {"tags":["support"],"app":"null/null","format":"markdown"} | ||||||
created | 2018-06-21 07:15:03 | ||||||
last_update | 2018-06-21 07:15:03 | ||||||
depth | 1 | ||||||
children | 0 | ||||||
last_payout | 2018-06-28 07:15:03 | ||||||
cashout_time | 1969-12-31 23:59:59 | ||||||
total_payout_value | 0.164 HBD | ||||||
curator_payout_value | 0.053 HBD | ||||||
pending_payout_value | 0.000 HBD | ||||||
promoted | 0.000 HBD | ||||||
body_length | 58 | ||||||
author_reputation | 557,563,606,581,756 | ||||||
root_title | "[코딩문제풀기 1일차] Peak Index in a Mountain Array" | ||||||
beneficiaries |
| ||||||
max_accepted_payout | 1,000,000.000 HBD | ||||||
percent_hbd | 10,000 | ||||||
post_id | 61,601,363 | ||||||
net_rshares | 108,817,363,866 | ||||||
author_curate_reward | "" |
voter | weight | wgt% | rshares | pct | time |
---|---|---|---|---|---|
virus707 | 0 | 108,206,973,468 | 1% | ||
holykw | 0 | 610,390,398 | 100% |