给定一个 n
个元素有序的(升序)整型数组 nums
和一个目标值 target
,写一个函数搜索 nums
中的 target
,如果目标值存在返回下标,否则返回 -1
。
示例 1:
输入:nums
= [-1,0,3,5,9,12],target
= 9 输出: 4 解释: 9 出现在nums
中并且下标为 4
示例 2:
输入:nums
= [-1,0,3,5,9,12],target
= 2 输出: -1 解释: 2 不存在nums
中因此返回 -1
# include<iostream>
# include <vector>
using namespace std;
class Solution {
public:
int index = -1; //返回找到的下标
int p = 0;
int search(vector<int>& nums, int target) {
for (auto it = nums.begin(); it != nums.end(); ++it, p++) {
if (target == *it) {
index = p;
break;
}
}
return index;
}
};
int main()
{
std::vector<int> nums = {-1, 0, 3, 5, 9, 12,};
int target = 9;
int index;
Solution Solution;
index = Solution.search(nums, target);
cout << index << endl;
}