[LeetCode] 34. Find First and Last Position of Element in Sorted Array
問題の説明
問題を解く
時間複雑度:O(logn)
基本的にはバイナリ検索を使用しますがnums[mid]=targetの場合、追加の親インデックス検索(endを検索するバイナリ検索)とサブインデックス検索(startを検索するバイナリ検索)が行われます.
+)後で反復する(関数パラメータ部分が汚い)
ソースコード(JAVA)
class Solution {
private int start, end;
public int[] searchRange(int[] nums, int target) {
int[] result = new int[2];
start = end = -1;
BinarySearch(nums, 0, nums.length - 1, target, true);
BinarySearch(nums, 0, nums.length - 1, target, false);
result[0] = start;
result[1] = end;
return result;
}
public void BinarySearch(int[] nums, int s, int e, int target, boolean isFindStart) {
int mid = (s + e) / 2;
if (s <= e) {
if (nums[mid] < target) BinarySearch(nums, mid + 1, e, target, isFindStart);
else if (nums[mid] > target) BinarySearch(nums, s, mid - 1, target, isFindStart);
else {
if (isFindStart == true) {
start = mid;
BinarySearch(nums, s, mid - 1, target, isFindStart);
}else {
end = mid;
BinarySearch(nums, mid + 1, e, target, isFindStart);
}
}
}
}
}
Reference
この問題について([LeetCode] 34. Find First and Last Position of Element in Sorted Array), 我々は、より多くの情報をここで見つけました https://velog.io/@ddongh1122/LeetCode-34.-Find-First-and-Last-Position-of-Element-in-Sorted-Arrayテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol