Skip to content

Commit 5c6bbcb

Browse files
committed
二分查找变异写法
1 parent 568daa2 commit 5c6bbcb

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@
167167
- 一个在线文档系统,文档可以被编辑,如何防止多人同时对同
168168
- 一份文档进行编辑更新。
169169
- 线上系统突然变得异常缓慢,你如何查找问题。
170-
- [说说你平时用到的设计模式](http://tech.hunts.work/2015/09/01/%E7%B3%BB%E7%BB%9F%E6%9E%B6%E6%9E%84/%E7%B3%BB%E7%BB%9F%E6%9E%B6%E6%9E%84-%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/#2-%E7%AE%80%E5%8D%95%E5%B7%A5%E5%8E%82simple-factory)
170+
- [说说你平时用到的设计模式](https://github.com/Snailclimb/JavaGuide/blob/master/Java%E7%9B%B8%E5%85%B3/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F.md)
171171
- [Dubbo的原理,有看过源码么,数据怎么流转的,怎么实现集群,负载均衡,服务注册和发现,重试转发,快速失败的策略是怎样的 。](https://blog.csdn.net/he90227/article/details/70157046/)
172172
- 一次RPC请求的流程是什么。
173173
- [自己实现过rpc么,原理可以简单讲讲。Rpc要解决什么问题。](https://mp.weixin.qq.com/s/kHcbIgMFNB0np6olcPch4w)

src/main/java/com/algorithm/study/demo/algorithm/FindProject.java

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
public class FindProject {
1515
public static void main(String[] args) {
1616

17-
int[] is=new int[]{3,5,6,7,10};
18-
System.out.println(binary_search_xiaoyu(is,10));
17+
int[] is=new int[]{4,5,6,7,0,1,2};
18+
System.out.println(binary_search_33(is,4));
1919
// System.out.println(binarySearch(is,2));
2020
// Shape redRectangle = new RedShapeDecorator(new Rectangle());
2121
// redRectangle.doShaper();
@@ -213,4 +213,42 @@ public static int binary_search_xiaoyu(int[] srcArray,int des){
213213
}
214214
return -1;
215215
}
216+
217+
/**
218+
* 假设按照升序排序的数组在预先未知的某个点上进行了旋转
219+
* ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
220+
* 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
221+
* @return
222+
*/
223+
public static int binary_search_33(int[] nums,int target){
224+
if (nums.length==0) return -1;
225+
if (nums.length==1){
226+
if (nums[0]==target){
227+
return 0;
228+
}else{
229+
return -1;
230+
}
231+
}
232+
int left=0;
233+
int right=nums.length-1;
234+
int middle=0;
235+
while (left<=right){
236+
middle=(left+right)>>1;
237+
if (nums[middle]==target) return middle;
238+
if (nums[middle]>=nums[right]){
239+
if(nums[left]<=target&&target<nums[middle]){
240+
right = middle-1;
241+
}else{
242+
left = middle+1;
243+
}
244+
}else{
245+
if(nums[middle]<target&&target<=nums[right]){
246+
left = middle+1;
247+
}else{
248+
right = middle==0?middle:middle-1;
249+
}
250+
}
251+
}
252+
return -1;
253+
}
216254
}

0 commit comments

Comments
 (0)