描述
给定一个排序的整数数组(升序)和一个要查找的整数 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

这篇博客探讨了如何使用二分查找算法在已排序的整数数组中高效地寻找目标数值。通过示例代码展示了C语言实现的二分查找函数,该函数在O(logn)的时间复杂度内找到目标值的首次出现下标。同时,文章提出了挑战,即当数组元素数量超过2^32时,算法是否仍然有效。
552

被折叠的 条评论
为什么被折叠?



