leetcode oj 1
来源:互联网 发布:你有阿里云幕布么 编辑:程序博客网 时间:2024/06/06 05:22
Search Insert Position
http://blog.csdn.net/u012661091/article/details/47088989
这是leetcode 一道简单的OJ题,主要就是理解二分查找,这一题看起来很简单,但是不理解二分查找的话,做起来会有大大小小不少问题,
下面给出解析和答案
其实主要就是二分查找算法稍微变形一下,二分查找的过程是将有序数组一分为2,不停的循环,最终查找到目标所在的位置,如果目标不在数组当中,返回-1。本题则是如果数组中不存在该目标值,则返回该目标值插入的位置。
public int searchOrInsert(int[] sortedArray,int target){ int left=0; int right=sortedArray.length-1; int mid = 0; while(left<=right){ mid=(left+right)>>1; if(sortedArray[mid]==target) return mid; else if(sortedArray[mid]>target) right=mid-1; else left=mid+1; } return sortedArray[mid]<target?mid+1:mid; }
该算法仅仅需要在最后一步返回目标值的正确位置。这个位置如何判断呢?
假设输入参数为数组:1,3,3,5 target为4,
我们逐步进入算法看看,首先left=0;right=3;mid=1
target在mid的右边,left=mid+1也就是2,mid=2;right=3;
target在mid右边,left=mid+1也就是3,right=3,mid=3,此时target在mid左边,right=mid-1也就是2,注意这时已经不满足循环条件了,退出循环,判断该target值在mid的左边,于是该target应该在mid的位置插入,return mid。
反之如果最终target在mid右边,则target的插入位置在mid+1处。
0 0
- leetcode oj 1
- LeetCode OJ 1Two Sum
- LeetCode OJ : 1 Two Sum
- LeetCode-OJ
- leetcode oj
- leetCode OJ(1) Single Number
- LeetCode OJ Number of 1 Bits
- LeetCode OJ Summary,Problems 1 - 15
- LeetCode Number of 1 Bits 刷题 OJ
- <LeetCode OJ> 191. Number of 1 Bits
- [leetcode oj 191]Number of 1 Bits
- 笔试题14. LeetCode OJ (1)
- LeetCode OJ 1 Two Sum [Easy]
- 【LeetCode OJ】Combinations
- 【LeetCode OJ】Valid Parentheses
- [LeetCode OJ]Single Number
- [LeetCode OJ]Same Tree
- LeetCode OJ:Single NumberII
- 发布iOS应用(Xcode5)到App Store详细解析
- 【Trie】bzoj1954——我终于当了权限狗了!
- 黑马程序员——10,线程
- 使用PHP的CURL模拟POST采集开了viewstate的asp.net网页数据
- POJ 2785 4 Values whose Sum is 0 (对半分解 二分搜索)
- leetcode oj 1
- Android中Handler与Thread的区别
- android沉浸式状态栏
- RecyclerView实现瀑布流布局
- App Store 审核指南中文翻译
- 英语学习--chap17 形容词从句简化
- C/C++中的联合体union及CPU大小端判定
- Linux的磁盘管理
- iOS学习笔记--(c基础题9)