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 ?。菜片F(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++?創(chuàng)建型設(shè)計模式工廠方法Factory?Method示例詳解
這篇文章主要為大家介紹了c++?創(chuàng)建型設(shè)計模式工廠方法Factory?Method示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
C++基于遞歸和非遞歸算法判定兩個二叉樹結(jié)構(gòu)是否完全相同(結(jié)構(gòu)和數(shù)據(jù)都相同)
這篇文章主要介紹了C++基于遞歸和非遞歸算法判定兩個二叉樹結(jié)構(gòu)是否完全相同,若判斷二叉樹的結(jié)構(gòu)和數(shù)據(jù)都相同則為完全相同.涉及C++二叉樹的創(chuàng)建、遍歷、比較等相關(guān)操作技巧,需要的朋友可以參考下2017-05-05
C++使用WideCharToMultiByte函數(shù)生成UTF-8編碼文件的方法
用來映射Unicode字符串的WideCharToMultiByte函數(shù)經(jīng)常被用來進行UTF-8編碼的轉(zhuǎn)換,以下我們將看到C++使用WideCharToMultiByte函數(shù)生成UTF-8編碼文件的方法,首先先來對WideCharToMultiByte作一個詳細的了解:2016-06-06
關(guān)于C++中sort()函數(shù)的用法,你搞明白了沒
這篇文章主要介紹了關(guān)于C++中sort()函數(shù)的用法,并通過三種方法介紹了按降序排列的實現(xiàn)代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03

