【LeetCode】35. 搜索插入位置(C++实现)
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode】35. 搜索插入位置(C++实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
傳送門:https://leetcode-cn.com/problems/search-insert-position/
一、題目描述
給定一個排序數組和一個目標值,在數組中找到目標值,并返回其索引。如果目標值不存在于數組中,返回它將會被按順序插入的位置。
你可以假設數組中無重復元素。
二、示例
示例 1:
輸入: [1,3,5,6], 5
輸出: 2
示例 2:
輸入: [1,3,5,6], 2
輸出: 1
示例 3:
輸入: [1,3,5,6], 7
輸出: 4
示例 4:
輸入: [1,3,5,6], 0
輸出: 0
三、分析
遍歷數組,依次進行比較
四、實現
class Solution { public:int searchInsert(vector<int>& nums, int target) {int i = 0;for(int j = 0; j < nums.size(); j++){if(nums[j] == target)return j;else if(nums[j] < target){i++;}}return i;} };總結
以上是生活随笔為你收集整理的【LeetCode】35. 搜索插入位置(C++实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Pandas】qcut和cut的区别
- 下一篇: 用Scikit-learn和Tensor