[M] 34. Find First and Last Position of Element in Sorted Array

YJ·5일 전

leetcode

목록 보기
85/100

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

문제

O(logn)O(logn) 시간 내에! 정렬된 배열에서 target 숫자가 나오는 구간 index 반환. 없으면 (-1,-1) 반환

답안

public int[] searchRange(int[] nums, int target) {
	int left = lowerBound(nums, target);
	if (left == nums.length || nums[left] != target) {
		return new int[]{-1, -1};
	}
	int right = lowerBound(nums, target + 1) - 1;
	return new int[]{left, right};
}

public int lowerBound(int[] nums, int target) {
	int left = 0;
	int right = nums.length;
	while (left < right) {
		int mid = left + (right - left) / 2;
		if (nums[mid] < target) {
			left = mid + 1;
		} else {
			right = mid;
		}
	}
	return left;
}

메모

O(logn)O(logn) 시간 내에.. -> Binary Search!
Lower Bound 찾는 함수가 이렇게나 유용하다..

  • right 은 nums.length -1 이 아닌 nums.length 에서 시작한다는 것
  • target 값이 딱 없으면 그것보다 큰 숫자가 시작하는 위치를 반환한다는 점
  • target 값이 모든 원소보다 크면 nums.length 를 반환한다는 것
profile
Hello

0개의 댓글