📄 문제
- 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
'TEAM 알고싶다 > 성공 문제' 카테고리의 다른 글
[LeetCode] 41. First Missing Positive (처음 누락된 양수?) (0) | 2022.06.13 |
---|---|
[프로그래머스] JavaScript - 오픈채팅방 (0) | 2022.06.09 |
[프로그래머스] JavaScript - 구명보트 (0) | 2022.06.06 |
[LeetCode] 4. Median of Two Sorted Arrays (정렬된 두 배열의 중앙값) (0) | 2022.06.03 |
[프로그래머스] JavaScript - 평균 구하기 (0) | 2022.05.30 |