greenkang
그린 개발log
greenkang
전체 방문자
오늘
어제
  • 분류 전체보기 (28)
    • 알고리즘 (20)
    • MySQL (0)
    • 생각 (0)
    • 컴퓨터구조 (6)
    • Spring · SpringBoot (1)
    • Java (1)
    • 장애 대응 회고 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 41. First Missing Positive
  • 파이썬
  • 프로그래머스
  • TOPCODER알고리즘트레이닝
  • 컴퓨터구조
  • 장애 대응 회고
  • 어셈블리어
  • 리트코드
  • 백준 24479번 자바
  • 자바
  • 프로그래머스 거리두기 java
  • python
  • 백준 1065번 자바
  • 백준 17265번
  • 프로그래머스 거리두기 자바
  • java
  • 백준7569
  • 백준7569 java
  • 백준
  • 알고리즘

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
greenkang

그린 개발log

[리트코드] 34. Find First and Last Position of Element in Sorted Array
알고리즘

[리트코드] 34. Find First and Last Position of Element in Sorted Array

2022. 5. 31. 17:46

문제 간단 설명 

정수형 배열에서 특정 숫자의 시작 위치와 마지막 위치를 찾아서 배열에 담아 반환한다. 단! 시간복잡도 log n 안에 해결할 것!

 

풀이 방법

1. 배열을 돌며 target을 찾는다. 

2. target과 같은 값을 처음 만난다면 시작 위치와 마지막 위치를 해당 위치로 변경한다.

3. 처음 만난게 아니라면 마지막 위치만 해당 위치로 변경한다.

4. target보다 값이 크다면 반복문 끝까지 가지 않고 빠져나간다.

 

코드

class Solution {
    public int[] searchRange(int[] nums, int target) {
        
        int[] result = {-1, -1};
        for(int idx = 0; idx < nums.length; idx++) {
            
            if(nums[idx] == target) {
                
                if(result[0] == -1) result[0] = idx;
                result[1] = idx;
                
            }else if(nums[idx] > target) break;
            
        }
        
        return result;
    }
}

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

 

'알고리즘' 카테고리의 다른 글

[리트코드] 41. First Missing Positive  (0) 2022.06.12
[프로그래머스] 오픈채팅방  (0) 2022.06.07
[프로그래머스] 구명보트  (0) 2022.06.04
[리트코드] 4. Median of Two Sorted Arrays  (0) 2022.06.03
[프로그래머스] 평균 구하기  (0) 2022.05.30
    '알고리즘' 카테고리의 다른 글
    • [프로그래머스] 오픈채팅방
    • [프로그래머스] 구명보트
    • [리트코드] 4. Median of Two Sorted Arrays
    • [프로그래머스] 평균 구하기
    greenkang
    greenkang

    티스토리툴바