알고리즘
[리트코드] 34. Find First and Last Position of Element in Sorted Array
greenkang
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