Skip to content

Instantly share code, notes, and snippets.

@kismet-
Last active October 9, 2023 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kismet-/4a2c4d70e57acb2a9a14d689df03a2b3 to your computer and use it in GitHub Desktop.
Save kismet-/4a2c4d70e57acb2a9a14d689df03a2b3 to your computer and use it in GitHub Desktop.
import "dart:convert";
List<int> search(List<int> nums, int target) {
List<int> result = [-1, -1];
int left = findLeft(nums, target);
if (left == -1) {
return result;
}
int right = findRight(nums, target);
result[0] = left;
result[1] = right;
return result;
}
int findLeft(List<int> nums, int target) {
int left = 0;
int right = nums.length - 1;
int boundary = -1;
while (left <= right) {
int mid = left + (right - left) ~/ 2;
if (nums[mid] == target) {
boundary = mid;
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return boundary;
}
int findRight(List<int> nums, int target) {
int left = 0;
int right = nums.length - 1;
int boundary = -1;
while (left <= right) {
int mid = left + (right - left) ~/ 2;
if (nums[mid] == target) {
boundary = mid;
left = mid + 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return boundary;
}
void main() {
List<int> nums1 = [5, 7, 7, 8, 8, 10];
int target1 = 8;
print(search(nums1, target1));
List<int> nums2 = [5, 7, 7, 8, 8, 10];
int target2 = 6;
print(search(nums2, target2));
List<int> nums3 = [];
int target3 = 0;
print(search(nums3, target3));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment