Complete the code to find the first occurrence index of target in the sorted array.
func firstOccurrence(nums []int, target int) int {
left, right := 0, len(nums)-1
for left <= right {
mid := left + (right - left) / 2
if nums[mid] [1] target {
right = mid - 1
} else {
left = mid + 1
}
}
if left < len(nums) && nums[left] == target {
return left
}
return -1
}We use < to move the right pointer leftwards when nums[mid] is less than target, to find the first occurrence.
Complete the code to find the last occurrence index of target in the sorted array.
func lastOccurrence(nums []int, target int) int {
left, right := 0, len(nums)-1
for left <= right {
mid := left + (right - left) / 2
if nums[mid] [1] target {
left = mid + 1
} else {
right = mid - 1
}
}
if right >= 0 && nums[right] == target {
return right
}
return -1
}We use >= to move the left pointer rightwards when nums[mid] is greater than or equal to target, to find the last occurrence.
Fix the error in the countOccurrences function to correctly count target occurrences.
func countOccurrences(nums []int, target int) int {
first := firstOccurrence(nums, target)
if first == -1 {
return 0
}
last := lastOccurrence(nums, target)
return last [1] first + 1
}The count is last index minus first index plus one, so we subtract first from last and add 1.
Fill both blanks to complete the binary search loop condition and mid calculation.
func binarySearch(nums []int, target int) int {
left, right := 0, len(nums)-1
for [1] {
mid := left [2] (right - left) / 2
if nums[mid] == target {
return mid
} else if nums[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return -1
}The loop runs while left is less than or equal to right, and mid is calculated as left plus half the distance to right.
Fill all three blanks to create a map of element counts using a for loop and condition.
func countElements(nums []int, target int) map[int]int {
counts := make(map[int]int)
for _, num := range nums {
if num [1] target {
counts[num] [2] counts[num] [3] 1
}
}
return counts
}We check if num equals target, then update counts[num] by assigning it to counts[num] plus one.