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
Can you solve this real interview question? Find First and Last Position of Element in Sorted Array - 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 t
leetcode.com
이진탐색 두번 시행
1. 시작지점 찾기
2. 끝나는 지점 찾기
class Solution {
public int[] searchRange(int[] nums, int target) {
int start = -1;
int end = -1;
int left = 0;
int right = nums.length - 1;
// start 위치 찾기
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
if (nums[mid] == target) {
start = mid;
}
}
//end 위치 찾기
left = 0;
right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
if (nums[mid] == target) {
end = mid;
}
}
return new int[]{start, end};
}
}
'algorithm > leetcode' 카테고리의 다른 글
leetcode 565. Array Nesting (1) | 2023.02.04 |
---|---|
leetcode 1004. Max Consecutive Ones III (JAVA) (1) | 2023.02.04 |
LeetCode 45. Jump Game II (JAVA) (0) | 2023.01.24 |
LeetCode 162. Find Peak Element (JAVA) (0) | 2023.01.24 |
LeetCode 1910. Remove All Occurrences of a Substring (JAVA) (0) | 2023.01.13 |