内容中心

2026年知名的SCADA系统数据采集稳定合作公司-深圳市中南新智造科技有限公司

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 of len(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

  1. Initialization:

    • low starts at the first index (0), high at the last index (len(arr)-1).
    • result is set to -1 (default for no target).
  2. Binary Search Loop:

    • Mid Calculation: mid = (low + high) // 2 (integer division to avoid floating points).
    • Target Found: If arr[mid] == target, update result to mid and move high left (mid-1) to look for an earlier occurrence.
    • Target in Right Half: If arr[mid] < target, shift low to mid+1.
    • Target in Left Half: If arr[mid] > target, shift high to mid-1.
  3. Edge Cases:

    • Empty array: len(arr) ==0 → returns -1.
    • Target not present: result remains -1.

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 0 to len(arr)-1.
  • Loop Conditions: Use low <= high for 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

深圳市中南新智造科技有限公司

深圳市中南新智造科技有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?