๊ฐœ๋ฐœ/๐Ÿ’ฌ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ

[leetCode] 34. Find First and Last Position of Element in Sorted Array - Javascript

๋ฐ(Ming) ๐Ÿˆ‍โฌ› 2023. 11. 10. 10:32
728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ 

Given an array of integers nums sorted in non - decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.

 

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Example 3:

Input: nums = [], target = 0
Output: [-1,-1]

 

Constraints:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • nums is a non-decreasing array.
  • -109 <= target <= 109

 

 

๋น„๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์–ด์žˆ๋Š” ์ˆซ์ž ๋ฐฐ์—ด์„ ์ฃผ๊ณ  ์ฃผ์–ด์ง„ ํƒ€์ผ“ ๋ฐธ๋ฅ˜๋ฅผ ์ฐพ์•„์„œ ์ฒ˜์Œ ํฌ์ง€์…˜๊ณผ ๋ ํฌ์ง€์…˜์„ ๋ฐ˜ํ™˜ํ•˜์‹œ์˜ค 

๋งŒ์•ฝ์— ํƒ€์ผ“์ด ์—†๋‹ค๋ฉด [-1, -1]์„ ๋ฐ˜ํ™˜ํ•˜์‹œ์˜ค

๋น…์˜ค ์ด์ง„๊ฒ€์ƒ‰์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ์“ฐ์‹œ์˜ค- ? 

 

 

 

*๋น„๋‚ด๋ฆผ์ฐจ์ˆœ ๋œป

๋‚ด๋ฆผ์ฐจ์ˆœ์€ ์ ์  ๊ฐ์†Œํ•˜๋Š” ์ˆ˜์—ด์ด๊ณ  ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ์€ ์ ์  ์ฆ๊ฐ€ํ•˜๋Š” ์ˆ˜์—ด์ž…๋‹ˆ๋‹ค. ์˜คํžˆ๋ ค ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ์€ ์˜ค๋ฆ„์ฐจ์ˆœ๊ณผ ๋น„์Šทํ•œ๋ฐ, ์ฐจ์ด์ ์€ ์˜ค๋ฆ„์ฐจ์ˆœ์€ ์ธ์ ‘ํ•œ ๋‘ ์ˆ˜๊ฐ€ ๊ฐ™์„ ์ˆ˜๋„ ์žˆ๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ๋ช…ํ™•ํ•˜๊ฒŒ ์•Œ๋ ค์ฃผ์ง€ ์•Š์ง€๋งŒ ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ์€ ๊ฐ™์„ ์ˆ˜๋„ ์žˆ์Œ์„ ๋ช…ํ™•ํžˆ ํ•ด์ค€ ๊ฒƒ์ด๋ผ๊ณ  ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.


ํ•ด๊ฒฐ ์ฝ”๋“œ

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var searchRange = function(nums, target) {
    let temp =[]
   
    // ์ฃผ์–ด์ง„ ์ธ์ง€์˜ ๊ธธ์ด๊ฐ€ 0์ผ ๋•Œ 
    if(nums.length == 0) {
        return [-1, -1]
        
    // ์ธ์ž์˜ ๊ธธ์ด๊ฐ€ 0์ด ์•„๋‹ ๋•Œ
    }else{
        
        //์„ ํ˜•๊ฒ€์ƒ‰์œผ๋กœ ๋Œ๋ฉด์„œ ํ•ด๋‹น target ์ธ๋ฑ์Šค ์ฐพ์•„์„œ array์— ๋„ฃ์–ด์ฃผ๊ธฐ
    for(let i=0; i<nums.length; i++ ){
        if(nums[i] === target){
            temp.push(i)
        }
    }
    
    // ๋งŒ์•ฝ์— ๋งž๋Š”๊ฒŒ ์—†์–ด์„œ ์ธ๋ฑ์Šค๊ฐ€ ์•ˆ ๋“ค์–ด๊ฐ”๋‹ค๋ฉด 
    if(temp.length == 0){
        temp= [-1, -1]
        
    // ๋“ค์–ด๊ฐ„ ์ธ๋ฑ์Šค๊ฐ€ ์žˆ๋‹ค๋ฉด ์ œ์ผ ์ฒ˜์Œ๊บผ๋ž‘ ์ œ์ผ ๋๋ถ€๋ถ„๋งŒ ์ฐพ์•„์„œ ๋„ฃ์–ด์ฃผ๊ธฐ 
    }else{
        temp = [temp[0], temp[temp.length-1]]
    }
    }
    
    return temp 
    
};

 

 

 

 

 

 

 

 

728x90