낭만개발자
낭만개발자
낭만개발자
전체 방문자
오늘
어제
  • 분류 전체보기 (57)
    • Web) HTML & CSS (5)
    • Web) HTTP (2)
    • 언어) Java (2)
    • 언어) Python (6)
    • 언어) PHP (1)
    • Linux (2)
    • 데이터 관리) Pandas (4)
    • Algorithms (13)
    • 개발자 역량 (4)
    • 프로젝트 (14)
      • Django 초기 프로젝트 (1)
      • CatCoDog _ 반려동물 식품 판매 사이트 (9)
      • 개인 홈서버 프로젝트 (2)
      • 이력핏 : AI가 추천해주는 이력서 (2)
    • 문제와 사고 (2)
    • ETC (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • algorithm
  • 파이썬 자료형
  • 오늘의 문제
  • css
  • leetcode88
  • Number Of Island
  • WEB
  • python basic
  • Java
  • python operator
  • django setting
  • css 포지션
  • Merge Sorted Array
  • 장고 초기 세팅
  • python
  • css 위치변경
  • JWT 웹
  • 파이썬 숫자형
  • 파이썬
  • catcodog
  • 파이썬 기초
  • Leetcode
  • Unique Paths
  • 리눅스
  • css 기본
  • 파이썬 기본
  • rainbow table
  • 웹개발
  • css basic
  • dp

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
낭만개발자

낭만개발자

[Algorithm] Leetcode 34. Find First and Last Position of Element in Sorted Array (java)
Algorithms

[Algorithm] Leetcode 34. Find First and Last Position of Element in Sorted Array (java)

2024. 1. 25. 23:39

풀이 코드

class Solution {
     public int[] searchRange(int[] nums, int target) {
        boolean isStart = true;
        
        int[] ans = new int[2];
        ans[0] = getStartOrEnd(isStart, target, nums);
        ans[1] = getStartOrEnd(!isStart, target, nums);
        return ans;            
    }
    
     public int getStartOrEnd(boolean isStart, int target, int[] nums){ 
        int left = 0;
        int right = nums.length - 1;
        int num = -1; 
    
        while(left <= right){
            int mid = left + (right - left) / 2;  
            if(nums[mid] < target){
                left = mid + 1;
            }else if(nums[mid] > target){
                right = mid - 1;
            }else{
                if(isStart){
                    right = mid - 1;
                }else{
                    left = mid + 1;
                }
                num = mid;
            }       
        }
        return num;   
    }
}

 

 

사고 과정

오늘도 array,, sorted array,, 

 

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

O(log N)의 시간복잡도로, 주어진 sorted array 'nums' 안의 target의 구간을 반환해주면 되는 문제!!

(만약 target이 존재하지 않는다면 [-1, -1]을 반환!

 

문제에서 노골적으로 O(logN)을 요구하는데 Binary Search를 안 쓸 이유가 없을 것 같다. 

 

지난번 Binary Search 문제와 접근법은 동일하지만, 

https://highandbrightdev.tistory.com/entry/A100C-Leetcode-704-Binary-Search-java

 

[A100C_day 1] Leetcode 704. Binary Search (java)

문제 링크 https://leetcode.com/problems/binary-search/ LeetCode - The World's Leading Online Programming Learning Platform Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your nex

highandbrightdev.tistory.com

문제는 target이 여러개 존재하는 경우, 그 범위를 반환해줄 때인 것 같은데, 

 

기껏 binary search 로 target을 찾아놓고, linear하게 target의 범위를 찾는다면, 최악의 경우 O(N)의 시간복잡도가 걸린다. 

(nums의 요소들이 모두 target일 경우, 결국 시간 복잡도는 O(N)이므로..!!)

 

따라서 target의 범위도 binary search를 이용해서 찾으면 되는 문제!!

 

코드 상의 특이한 점이라면 getStartOrLast 메서드를 따로 선언해서 target의 범위를 구했다는 점. 

그 외에는 앞선 binary search 문제와 동일하다!

 

오알완..!

 

 

 

 

저작자표시 (새창열림)

'Algorithms' 카테고리의 다른 글

[Algorithm] Leetcode 200. Number of Islands (java)  (1) 2024.01.28
[Algorithm] Leetcode 1. Two Sum(java)  (0) 2024.01.26
[A100C_day 3] Leetcode 79. Word Search (java)  (0) 2024.01.24
[A100C_day 2] Leetcode 88. Merge Sorted Array (java)  (0) 2024.01.23
[A100C_day 1] Leetcode 704. Binary Search (java)  (0) 2024.01.22
    낭만개발자
    낭만개발자
    Learning By Doing!💪

    티스토리툴바