add: 220326 [cpp]

This commit is contained in:
Lam Haoyin 2022-03-26 09:38:21 +08:00
parent 4b19e7c2d4
commit 9e02748dd4
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 17 additions and 1 deletions

16
cpp/2203/220326.cpp Normal file
View File

@ -0,0 +1,16 @@
#include <vector>
#include <algorithm>
/**
* 704. Binary Search
* Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.
* You must write an algorithm with O(log n) runtime complexity.
*/
class Solution {
public:
static int search(const std::vector<int>& nums, int target) {
auto it = std::lower_bound(nums.begin(), nums.end(), target);
return (it == nums.end() || *it != target) ? -1 : std::distance(nums.begin(), it);
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220325-CN.cpp)
ADD_EXECUTABLE(2203 220326.cpp)