14 · 二分查找(LintCode,算法,简单)失败

描述

给定一个排序的整数数组(升序)和一个要查找的整数 target,用O(logn)O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1

样例

样例 1:

输入:

数组 = [1,4,4,5,7,7,8,9,9,10]
target = 1

输出:

0

解释:

第一次出现在第0个位置。

样例 2:

输入:

数组 = [1, 2, 3, 3, 4, 5, 10]
target = 3

输出:

2

解释:

第一次出现在第2个位置

样例 3:

输入:

数组 = [1, 2, 3, 3, 4, 5, 10]
target = 6

输出:

-1

解释:

没有出现过6, 返回-1

挑战

如果数组中的整数个数超过了2^{32}232,你的算法是否会出错?

C语言:

/**
 * You can create and use dynamic array in your code.
 * You can replace "int" to any other type you want to put in the array, e.g. float, char*, list_node*.
 * Create an empty int array:         int* arr = NULL;
 * Add an element to the back:        cvector_push_back(arr, 42);
 * Remove an element from the back:   cvector_pop_back(arr);
 * Get size of a dynamic array:       cvector_size(arr)
 * For other macros, see https://github.com/eteran/c-vector
 */
/**
 * @param nums: The integer array.
 * @param target: Target to find.
 * @return: The first position of target. Position starts from 0.
 */
int binary_search(int* nums, int target) {
    // write your code here
    int amount=0,len=0;
    int left, right, mid;
    for(int i=0;;i++)
    {
        if(nums[i]=='\0')
        {
            len=i;
            break;
        }
    }
    left=0;
    right=len-1;
    mid=(right-left)/2;
    while(1)
    {
        if(nums[left]==target)
            return left;
        else if(nums[right]==target)
            return right;
        else if(nums[mid]==target)
            return mid;
        else if(nums[mid]>target)
        {
            right=mid-1;
        }
        else if(nums[mid]<target)
        {
            left=mid+1;
        }
        mid=(right-left)/2;
    }
    return -1;
}

Compile Error        0%

异常信息

/code/Main.c: In function 'main':
/code/Main.c:17:15: error: 'data' undeclared (first use in this function)
   17 |         fgets(data, MAX_LEN, td->fin);
      |               ^~~~
/code/Main.c:17:15: note: each undeclared identifier is reported only once for each function it appears in

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值