Find First and Last Position of Element in Sorted Array Solutions in Go
Number 34
Difficulty Medium
Acceptance 36.2%
Link LeetCode
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodefunc searchRange(nums []int, target int) []int {return []int{searchFirstEqualElement(nums, target), searchLastEqualElement(nums, target)}}// 二分查找第一个与 target 相等的元素,时间复杂度 O(logn)func searchFirstEqualElement(nums []int, target int) int {low, high := 0, len(nums)-1for low <= high {mid := low + ((high - low) >> 1)if nums[mid] > target {high = mid - 1} else if nums[mid] < target {low = mid + 1} else {if (mid == 0) || (nums[mid-1] != target) { // 找到第一个与 target 相等的元素return mid}high = mid - 1}}return -1}// 二分查找最后一个与 target 相等的元素,时间复杂度 O(logn)func searchLastEqualElement(nums []int, target int) int {low, high := 0, len(nums)-1for low <= high {mid := low + ((high - low) >> 1)if nums[mid] > target {high = mid - 1} else if nums[mid] < target {low = mid + 1} else {if (mid == len(nums)-1) || (nums[mid+1] != target) { // 找到最后一个与 target 相等的元素return mid}low = mid + 1}}return -1}// 二分查找第一个大于等于 target 的元素,时间复杂度 O(logn)func searchFirstGreaterElement(nums []int, target int) int {low, high := 0, len(nums)-1for low <= high {mid := low + ((high - low) >> 1)if nums[mid] >= target {if (mid == 0) || (nums[mid-1] < target) { // 找到第一个大于等于 target 的元素return mid}high = mid - 1} else {low = mid + 1}}return -1}// 二分查找最后一个小于等于 target 的元素,时间复杂度 O(logn)func searchLastLessElement(nums []int, target int) int {low, high := 0, len(nums)-1for low <= high {mid := low + ((high - low) >> 1)if nums[mid] <= target {if (mid == len(nums)-1) || (nums[mid+1] > target) { // 找到最后一个小于等于 target 的元素return mid}low = mid + 1} else {high = mid - 1}}return -1}