C++ 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。

本题应用二分查找法:
在升序数组 nums 中寻找目标值 target,对于特定下标 i,比较 nums[i] 和 target 的大小:
如果 nums[i] = =target,则下标 i 即为要寻找的下标;
如果 nums[i]>target,则target 只可能在下标 i 的左侧;
如果 nums[i]<target,则target 只可能在下标 i 的右侧。
基于上述事实,可以在有序数组中使用二分查找寻找目标值。

代码如下:

#include<stdio.h>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
    
    
public :int search(vector<int>& nums, int target) {
    
    
		int low = 0, high = nums.size() - 1;
		while (low <= high) {
    
    
			int mid = (high - low) / 2 + low;
			int num = nums[mid];
			if (num == target) {
    
    
				return mid;
			}
			else if (num > target) {
    
    
				high = mid - 1;
			}
			else {
    
    
				low = mid + 1;
			}
		}
		return -1;
	}
};
 void main() {
    
    
		vector<int>nums = {
    
     1,4,5,7,12,34,55 };
		int target = 7;
		Solution S ;
		int a = S.search(nums, target);
		cout << a << endl;
	}

由于每次查找都会将查找范围缩小一半,因此二分查找的时间复杂度是O(logn),其中 n 是数组的长度。
复杂度分析:
时间复杂度:O(logn),其中 n 是数组的长度。
空间复杂度:O(1)。

猜你喜欢

转载自blog.csdn.net/weixin_45358354/article/details/121549815