leetcode-Search Insert Position
来源:互联网 发布:阿里云cdn节点ip 编辑:程序博客网 时间:2024/06/11 07:35
题目描述
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.
Here are few examples.[1,3,5,6]
, 5 → 2[1,3,5,6]
, 2 → 1[1,3,5,6]
, 7 → 4[1,3,5,6]
, 0 → 0
解题思路
方法一,从前往后找,当target小于或者等于数组中某个数的时候,就返回这个数的下标即可,代码如下;
class Solution {public: int searchInsert(vector<int>& nums, int target) { if(nums.size()==0) return 0; int flag=-1; for(int i=0;i<nums.size();i++) { if(target<=nums[i]) { flag=i; break; } } if(flag==-1) { flag=nums.size(); } return flag; }};
方法二,利用二分查找法
代码如下:
class Solution {public: int searchInsert(vector<int>& nums, int target) { if(nums.size()==0) return 0; int low=0,high=nums.size()-1; while(low<=high) { int mid=(low+high)/2; if(target>nums[mid]) low=mid+1; else if(target<nums[mid]) high=mid-1; else return mid; } }};
0 0
- LeetCode: Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- [LeetCode]Search Insert Position
- [LeetCode] Search Insert Position
- LeetCode-Search Insert Position
- LeetCode - Search Insert Position
- LeetCode | Search Insert Position
- Leetcode: Search Insert Position
- 【LeetCode】Search Insert Position
- Leetcode Search Insert Position
- Leetcode: Search Insert Position
- LeetCode:Search Insert Position
- leetcode Search Insert Position
- LeetCode Search Insert Position
- JAVA学习第7天(2)java当中的异常2
- How to upload your project to GitHub
- oracle修改列的类型
- date0405/SingleTest.java
- 3.5 Mediator(中介者) -- 对象行为型模式
- leetcode-Search Insert Position
- maven常用插件
- date0405/StaticCodeDemo.java
- 线程的分离状态
- date0405/StaticDemo.java
- linux下卸载mysql
- 3.6 Memento(备忘录) -- 对象行为型模式
- 205 Isomorphic Strings
- myeclips10的svn插件安装