leetcode Search Input Position
来源:互联网 发布:移动网络下载不了电影 编辑:程序博客网 时间:2024/06/05 06:41
题目:https://oj.leetcode.com/problems/search-insert-position/
题意,用二分法,找到target在数组的位置,如果数组中没有,则找到它要插入的位置,默认数组无重复,并且target与数组也无重复
这一种是我的方法:
class Solution {public: int searchInsert(int A[], int n, int target) { int beg,end,mid; if(n==0) return 0; beg = 0;end =n-1; if(A[n-1]<target) return n;<span style="white-space:pre"></span>//超过数组的范围 if(A[0]>target) return 0;<span style="white-space:pre"></span><span style="font-family: Arial, Helvetica, sans-serif;">//超过数组的范围</span><span style="white-space:pre"></span> while(beg<end){ mid = (beg+end)>>1; if (A[mid] == target) return mid; else if(A[mid]<target) beg =mid+1; else end =mid; } return end; }};我在做while判断的时候,用的是小于,在target与Mid比较的时候如果mid>target的话,则end =mid,这样做有个不好的地方,就是当数组只有一个的时候,beg = end =0,target插入的位置就成了end=0了,所以还要比较一下是否超过数组的范围
下面是别人的代码:
class Solution {public: int searchInsert(int A[], int n, int target) { int low = 0,high = n - 1; while (low <= high){ int mid = (low + high) / 2; if(A[mid]==target) return mid; else if (A[mid] >target){ high = mid - 1; } else{ low = mid + 1; } } return low; }};
这样就不会有问题了,所以在用二分查找发的时候,用end =mid 还是mid+1,既然是mid+1的话,那么判断条件也从beg<end 变成beg <=end
0 0
- leetcode Search Input Position
- [leetcode][search] 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
- JQuery Mobile 学习笔记2-4:changePage()方法跳转页面
- 使用服务(内置)动态填充dropdownlist
- 【HDU2639】Bone Collector II
- IP3 比1DB压缩点 大10DB
- 按时间给表建立range分区
- leetcode Search Input Position
- 汉游天下公司的一些感悟
- Poj 2251 Dungeon Master(三维Dfs)
- 关于Cocos2d-x的一些认识(2)
- Android 百度地图 SDK v3_3_0 (三) ---离线地图
- TalkingData:2014年移动打车应用行业报告
- ios 编译过程中碰到std::ios_base::Init::~Init()错误的问题解决方法
- CI框架中封装Model
- 简单介绍 C语言中 三种if宏定义