장난꾸러기 현수

WooBuntu·2021년 3월 29일
0

JS 90제

목록 보기
31/33
  • 강의 듣기 전 풀이
function solution(arr) {
  const result = [];
  let right;
  let target;
  const limit = arr.length;
  for (let i = 0; i < limit - 1; i++) {
    const current = arr[i];
    const next = arr[i + 1];
    if (target && target <= next && current <= right)
      return result.concat(i + 1);
    if (!target && current >= next) {
      target = current;
      right = next;
      result.push(i + 1);
    }
  }
}
const result = solution([120, 127, 125, 130, 135, 135, 143, 152, 160]);
// const result = solution([120, 125, 152, 130, 135, 135, 143, 127, 160]);
// const result = solution([120, 130, 150, 150, 130, 150]);

console.log(result);
  • 강의 반영한 풀이
function solution(arr) {
  const answer = [];
  const originalArray = arr.slice();
  const sortedArray = arr.sort((a, b) => a - b);
  const limit = arr.length;
  for (let i = 0; i < limit; i++) {
    if (originalArray[i] !== sortedArray[i]) {
      answer.push(i + 1);
      if (answer.length == 2) return answer;
    }
  }
}
const result = solution([120, 127, 125, 130, 135, 135, 143, 152, 160]);
// const result = solution([120, 125, 152, 130, 135, 135, 143, 127, 160]);
// const result = solution([120, 130, 150, 150, 130, 150]);

console.log(result);

훨씬 깔끔하네...

0개의 댓글