To address problems requiring careful index handling, let’s focus on a common example: finding the first occurrence of a target in a sorted array with duplicates—a problem where index precision is critical.
Problem Statement
Given a sorted array of integers (possibly with duplicates), find the first index where the target appears. If not present, return -1.
Key Index Considerations
- Avoid off-by-one errors (e.g., using
len(arr)instead oflen(arr)-1). - Adjust pointers correctly to search for the first occurrence (not just any occurrence).
- Handle edge cases (empty array, target not found).
Solution Code
def find_first_occurrence(arr, target):
low = 0
high = len(arr) - 1
result = -1 # Default if target not found
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
result = mid # Candidate found, but check left for earlier occurrence
high = mid - 1 # Move left to find first occurrence
elif arr[mid] < target:
low = mid + 1 # Target is in right half
else:
high = mid - 1 # Target is in left half
return result
Explanation
-
Initialization:
lowstarts at the first index (0),highat the last index (len(arr)-1).resultis set to-1(default for no target).
-
Binary Search Loop:
- Mid Calculation:
mid = (low + high) // 2(integer division to avoid floating points). - Target Found: If
arr[mid] == target, updateresulttomidand movehighleft (mid-1) to look for an earlier occurrence. - Target in Right Half: If
arr[mid] < target, shiftlowtomid+1. - Target in Left Half: If
arr[mid] > target, shifthightomid-1.
- Mid Calculation:
-
Edge Cases:
- Empty array:
len(arr) ==0→ returns-1. - Target not present:
resultremains-1.
- Empty array:
Why This Works
By adjusting high to mid-1 when the target is found, we ensure we keep searching the left half for the first occurrence, not just any. This avoids missing earlier instances of the target in a sorted array with duplicates.
General Takeaways for Index Handling
- Check Boundaries: Always ensure indices stay within
0tolen(arr)-1. - Loop Conditions: Use
low <= highfor binary search (covers all elements). - Adjust Pointers: For first occurrence, move left after finding the target; for last occurrence, move right.
This approach applies to many index-sensitive problems (e.g., rotated sorted arrays, merging sorted arrays). Always test edge cases to validate index logic!
Answer: The solution for finding the first occurrence of a target in a sorted array is as above, with careful index management to avoid off-by-one errors and ensure correctness. For example, if the input array is [1,2,3,3,3,4] and target is 3, the output is 2.
# Example usage
arr = [1,2,3,3,3,4]
target =3
print(find_first_occurrence(arr, target)) # Output:2


作者声明:本文包含人工智能生成内容。