[Lintcode] 14. First Position of Target

14. 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
Example 1:
Input: [1,4,4,5,7,7,8,9,9,10],1
Output: 0

Explanation: 
the first index of  1 is 0.

Example 2:
Input: [1, 2, 3, 3, 4, 5, 10],3
Output: 2

Explanation: 
the first index of 3 is 2.

Example 3:
Input: [1, 2, 3, 3, 4, 5, 10],6
Output: -1

Explanation: 
Not exist 6 in array.

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

我的代码


class Solution:
    """
    @param nums: The integer array.
    @param target: Target to find.
    @return: The first position of target. Position starts from 0.
    """
    def binarySearch(self, nums, target):
        # write your code here
        l = 0
        r = len(nums)-1
        m = int((l+r)/2)
        while(l<=r):
            if nums[m]==target and ( m==0 or nums[m-1]<target):
                return m
            else:
                if nums[m]>=target:
                    r = m-1
                else:
                    l = m+1
                m = int((l+r)/2)
                
        return -1

思路:

二分法。
类似的题:

  • 时间复杂度: O(log(n))
  • 出错:注意是第一个target的元素!
`string::find_first_of()` 是 C++ 中 `std::string` 类的成员函数,用于在字符串中查找第一个匹配指定字符集中任一字符的位置。 该函数的语法如下: ```cpp size_t find_first_of(const string& str, size_t pos = 0) const noexcept; size_t find_first_of(const char* s, size_t pos = 0) const noexcept; size_t find_first_of(const char* s, size_t pos, size_t count) const noexcept; size_t find_first_of(char c, size_t pos = 0) const noexcept; ``` 参数说明: - `str`:要搜索的字符串。 - `s`:要搜索的 C 风格字符串。 - `pos`:搜索的起始位置,默认为 0。 - `count`:要搜索的 C 风格字符串的字符数。 - `c`:要搜索的单个字符。 返回值: - 如果找到匹配字符,则返回第一个匹配字符的位置。 - 如果未找到匹配字符,则返回 `string::npos`。 示例用法: ```cpp #include <iostream> #include <string> int main() { std::string str = "Hello, world!"; size_t found = str.find_first_of("el", 0); if (found != std::string::npos) { std::cout << "First occurrence of 'e' or 'l' is at position " << found << std::endl; } else { std::cout << "No occurrence of 'e' or 'l' found." << std::endl; } return 0; } ``` 输出结果: ``` First occurrence of 'e' or 'l' is at position 1 ``` 在上述示例中,`find_first_of()` 函数用于查找字符串 `str` 中第一个匹配字符集 "el" 中的字符的位置。由于字符 'e' 在位置 1 处首次出现,因此返回值为 1。 注意:`find_first_of()` 函数还有一个重载版本,可以接受一个 `std::initializer_list<char>` 参数,用于指定要搜索的字符集。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值