TEAM 알고싶다/성공 문제

[LeetCode] 34. Find First and Last Position of Element in Sorted Array (정렬된 배열에서 요소의 첫 번째 및 마지막 위치 찾기)

서크호 2022. 6. 1. 01:07

📄 문제

- nums 라는 내림차순으로 정렬된 정수 배열이 주어지면 주어진 target값의 시작 위치와 끝 위치를 찾기

- 주의점 : 반드시 OutPut은 ['시작', '끝'] 으로 length가 2여야 한다. + target이 없으면 [-1,-1] return

 

문제 사진


📝 나의 풀이

let searchRange = function (nums, target) {
  let answer = [];
  let newArr = [];
  nums.forEach((a, b) => {
    if (a == target) answer.push(b);
  });

  if (answer.length == 0) {
    return [-1, -1];
  } else {
    newArr = [answer[0], answer[answer.length - 1]];
  }
  return newArr;
};

딱 절반 정도의 속도와, 생각보다 적게 쓴 메모리?!


⌨ 접근법

1. nums 배열에서 target 과 일치하는 모든 요소를 담을 배열 answer + answer를 가공해서 답을 담을 newArr 배열 생성

2. 반복문으로 nums 요소들 마다 target과 일치하는 answer에 담는다.

3. (answer의 length == 0) => 빈 배열이거나, target과 일치하는 요소가 없다 == [-1,-1] return

4. (answer의 length != 0) => 1개 이상의 요소가 일치하니 첫번째 요소와 마지막 요소로 newArr = ['시작' , '끝'] 모양 생성 


📚 문제 링크

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

 

Find First and Last Position of Element in Sorted Array - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com