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 the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
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
Binary Search로 풀었으나. . 시간초과...ㅠㅠ 범위로 애 먹었다.
public class No34 {
public static int[] searchRange(int[] nums, int target) {
int start = 0, end = nums.length - 1;
int[] result = {-1, -1};
if(nums.length==0) {
return result;
}
while (nums[start] < nums[end]) {
int mid = start + (end - start)/2;
if (nums[mid] > target) {
end = mid - 1;
} else if (nums[mid] < target) {
start = mid + 1;
} else {
if(nums[start] == nums[mid]) {
end--;
} else {
start++;
}
}
}
if(nums[start]==nums[end] && nums[start]==target) {
result[0] = start;
result[1] = end;
}
return result;
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 844. Backspace String Compare (0) | 2022.05.25 |
---|---|
LeetCode 74. Search a 2D Matrix (0) | 2022.05.23 |
LeetCode 167. Two Sum II - Input Array Is Sorted (0) | 2022.05.18 |
LeetCode 283. Move Zeroes (0) | 2022.05.17 |
LeetCode 189. Rotate Array (0) | 2022.05.16 |