728x90
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/
public class Solution
{
public int[] SearchRange(int[] nums, int target)
{
return new int[] { GetStartIndex(nums, target), GetEndIndex(nums, target) };
}
private int GetStartIndex(int[] nums, int target)
{
int start = 0;
int end = nums.Length - 1;
int startIndex = -1;
while (start <= end)
{
int pivot = (start + end) / 2;
if (nums[pivot] < target)
{
start = pivot + 1;
}
else if (nums[pivot] > target)
{
end = pivot - 1;
}
else
{
startIndex = pivot;
end = pivot - 1;
}
}
return startIndex;
}
private int GetEndIndex(int[] nums, int target)
{
int start = 0;
int end = nums.Length - 1;
int endIndex = -1;
while (start <= end)
{
int pivot = (start + end) / 2;
if (nums[pivot] < target)
{
start = pivot + 1;
}
else if (nums[pivot] > target)
{
end = pivot - 1;
}
else
{
endIndex = pivot;
start = pivot + 1;
}
}
return endIndex;
}
}
728x90
'Programing > Algorithm' 카테고리의 다른 글
[LeetCode] 36. Valid Sudoku (0) | 2025.02.13 |
---|---|
[LeetCode] 33. Search in Rotated Sorted Array (0) | 2025.02.12 |
[LeetCode] 22. Generate Parentheses (0) | 2025.02.10 |
[LeetCode] 19. Remove Nth Node From End of List (0) | 2025.02.10 |
[LeetCode] 17. Letter Combinations of a Phone Number (0) | 2025.02.10 |