C++實現(xiàn)LeetCode(35.搜索插入位置)
[LeetCode] 35. Search Insert Position 搜索插入位置
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
這道題基本沒有什么難度,實在不理解為啥還是 Medium 難度的,完完全全的應(yīng)該是 Easy 啊(貌似現(xiàn)在已經(jīng)改為 Easy 類了),三行代碼搞定的題,只需要遍歷一遍原數(shù)組,若當(dāng)前數(shù)字大于或等于目標(biāo)值,則返回當(dāng)前坐標(biāo),如果遍歷結(jié)束了,說明目標(biāo)值比數(shù)組中任何一個數(shù)都要大,則返回數(shù)組長度n即可,代碼如下:
解法一:
class Solution { public: int searchInsert(vector<int>& nums, int target) { for (int i = 0; i < nums.size(); ++i) { if (nums[i] >= target) return i; } return nums.size(); } };
解法二:
class Solution { public: int searchInsert(vector<int>& nums, int target) { if (nums.back() < target) return nums.size(); int left = 0, right = nums.size(); while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] < target) left = mid + 1; else right = mid; } return right; } };
到此這篇關(guān)于C++實現(xiàn)LeetCode(35.搜索插入位置)的文章就介紹到這了,更多相關(guān)C++實現(xiàn)搜索插入位置內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C++實現(xiàn)LeetCode(38.計數(shù)和讀法)
- C++實現(xiàn)LeetCode(51.N皇后問題)
- C++實現(xiàn)LeetCode(77.Combinations 組合項)
- C++實現(xiàn)LeetCode(46.全排列)
- C++實現(xiàn)LeetCode(37.求解數(shù)獨)
- C++實現(xiàn)LeetCode(36.驗證數(shù)獨)
- C++實現(xiàn)LeetCode(34.在有序數(shù)組中查找元素的第一個和最后一個位置)
- C++實現(xiàn)LeetCode(33.在旋轉(zhuǎn)有序數(shù)組中搜索)
- C++實現(xiàn)LeetCode(39.組合之和)
相關(guān)文章
C/C++函數(shù)調(diào)用的幾種方式總結(jié)
本篇文章主要是對C/C++函數(shù)調(diào)用的幾種方式進(jìn)行了詳細(xì)的總結(jié)介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12C++實現(xiàn)LeetCode(65.驗證數(shù)字)
這篇文章主要介紹了C++實現(xiàn)LeetCode(65.驗證數(shù)字),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07C++實現(xiàn)圖片轉(zhuǎn)base64的示例代碼
Base64就是一種 基于64個可打印字符來表示二進(jìn)制數(shù)據(jù)的表示方法,本文主要為大家詳細(xì)介紹了如何使用C++實現(xiàn)圖片轉(zhuǎn)base64,需要的可以參考下2024-04-04