Complete the code to find the first occurrence of the target in the sorted array.
int firstOccurrence(const vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
result = mid;
right = mid [1] 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}When we find the target, we move the right pointer to mid - 1 to continue searching on the left side for the first occurrence.
Complete the code to find the last occurrence of the target in the sorted array.
int lastOccurrence(const vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
result = mid;
left = mid [1] 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}When the target is found, move the left pointer to mid + 1 to search the right side for the last occurrence.
Fix the error in the countOccurrences function to correctly calculate the count of target in the array.
int countOccurrences(const vector<int>& nums, int target) {
int first = firstOccurrence(nums, target);
if (first == -1) return 0;
int last = lastOccurrence(nums, target);
return last [1] first + 1;
}The count is last index minus first index plus one, so use '-' between last and first.
Fill both blanks to create a dictionary comprehension that maps each word to its length only if the length is greater than 3.
auto result = std::unordered_map<std::string, int>{};
for (const auto& word : words) {
if (word.size() [1] 3) {
result[word] = word[2]size();
}
}We check if word size is greater than 3 using '>' and get size using '()' after word.
Fill all three blanks to create a map of uppercase words to their lengths only if length is greater than 4.
std::unordered_map<std::string, int> result; for (const auto& word : words) { if (word.size() [1] 4) { std::string upper_word = word; std::transform(upper_word.begin(), upper_word.end(), upper_word.begin(), ::[2]); result[[3]] = word.size(); } }
We check if size is greater than 4, use 'toupper' to convert characters, and use 'upper_word' as the key in the map.