Leetcode81: Search Insert Position
来源:互联网 发布:淘宝店刷销量方法 编辑:程序博客网 时间:2024/05/22 03:27
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
两种方法,一种直接遍历,一种二分查找
class Solution {public: int searchInsert(vector<int>& nums, int target) { int size = nums.size(); if(size == 0) return 0; int i; for(i = 0; i < size; i++) { if(target <= nums[i]) return i; } return i; }};
class Solution {public: int searchInsert(vector<int>& nums, int target) { int size = nums.size(); int low = 0, high = size-1; while(low <= high) { int mid = (low+high)>>1; if(nums[mid] == target) return mid; else if(nums[mid] > target) high = mid-1; else low = mid+1; } if(high < 0) return 0; if(low >= size) return size; return low; }};
0 0
- Leetcode81: Search Insert Position
- LeetCode: Search Insert Position
- Search Insert Position
- LeetCode Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode : Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- [Leetcode] Search Insert Position
- LeetCode34:Search Insert Position
- Search Insert Position
- [35]Search Insert Position
- Search Insert Position
- Search Insert Position
- [LeetCode]Search Insert Position
- Search Insert Position
- [LeetCode] Search Insert Position
- Search Insert Position
- 自己写的shall函数集合
- 软件开发中的经验教训
- Android中spinner的简单用法(1)
- 混淆器ProGuard
- ListView数据重复现象,以及解决办法
- Leetcode81: Search Insert Position
- iOS中的堆和栈
- ionic项目中使用cordova插件支付宝支付
- HDU 5476 Explore Track of Point (2015年上海赛区网络赛I题)
- jquery.ajax 的例子
- 编译生成.NET DLL并调用
- android学习:在ListView显示对象信息、侦听列表事件
- ListCtrl虚拟列表---加载大数据
- 三层标签pop