First Position of Target

Description

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity. If the target number does not exist in the array, return -1.

Example
If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

Challenge
If the count of numbers is bigger than 2^32, can your code work properly?

Answer: In 32bit system, the std::vector cannot hold 2^32 elements. So, we can move to 64bit system with 48bit address.
Or we can use cluster to store the vector into distributed individuals.

  • Vector limit for 32bit,
    call std::vector<T>::max_size()
  • 2^32-1 for char 1 byte/element
  • 2^30-1 for int 4 bytes/element
  • 2^29-1 for double 8 bytes/element Link

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
class Solution {
public:
    /**
     * @param nums: The integer array.
     * @param target: Target number to find.
     * @return: The first position of target. Position starts from 0. 
     */
    int binarySearch(vector<int> &array, int target) {
        // write your code here
        if (array.empty()) {
            return -1;
        }
        int start = 0;
        int end = array.size()-1;
        while (start+1 < end) {
            int mid = start + (end-start)/2;
            // in the left region
            if (target == array[mid]) {
                end = mid;
            } else if (target < array[mid]) {
                end = mid;
            } else {
            // in the right region
            // if (target > array[mid]) {
                start = mid;
            }
        }
        if (target == array[start]) {
            return start;
        }
        if (target == array[end]) {
            return end;
        }
        return -1;
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""