From 9e02748dd432d5c213c42bd9bbf1edac79dcb2c6 Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Sat, 26 Mar 2022 09:38:21 +0800 Subject: [PATCH] add: 220326 [cpp] --- cpp/2203/220326.cpp | 16 ++++++++++++++++ cpp/2203/CMakeLists.txt | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 cpp/2203/220326.cpp diff --git a/cpp/2203/220326.cpp b/cpp/2203/220326.cpp new file mode 100644 index 0000000..da4d949 --- /dev/null +++ b/cpp/2203/220326.cpp @@ -0,0 +1,16 @@ +#include +#include + +/** + * 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& 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); + } +}; diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index e01461b..29f2853 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220325-CN.cpp) +ADD_EXECUTABLE(2203 220326.cpp)