首页 > 其他分享 >33. Search in Rotated Sorted Array

33. Search in Rotated Sorted Array

时间:2022-11-06 14:22:56浏览次数:47  
标签:Search end nums 33 mid return start int Sorted

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

 

 

public int search(int[] nums, int target) {
if (nums.length == 0)
return -1;
int minIdx = findMinIdx(nums); //先找出最小值的索引
if (target == nums[minIdx])
return minIdx;
int m = nums.length;
int start = (target > nums[m - 1]) ? 0 : minIdx;
int end = (target > nums[m - 1]) ? minIdx - 1 : m - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target)
return mid;
else if (target > nums[mid])
start = mid + 1;
else
end = mid - 1;
}
return -1;
}

public int findMinIdx(int[] nums) {
int start = 0, end = nums.length - 1;
while (start < end) {
int mid = start + (end - start) / 2;
if (nums[mid] > nums[end])
start = mid + 1;
else
end = mid;
}
return start;
}

 

标签:Search,end,nums,33,mid,return,start,int,Sorted
From: https://www.cnblogs.com/MarkLeeBYR/p/16862532.html

相关文章

  • 3.Elasticsearch核心概念
    6.1 核心概念6.1.1 索引Index一个索引就是一个拥有几分相似特征的文档的集合。比如说,你可以有一个客户数据的索引,另一个产品目录的索引,还有一个订单数据的索引。一个......
  • 33、Java——汽车租赁系统(对象+JDBC)
    ✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。本文目录​​覆盖知识​​​​项目需求​​​​设计步骤 ​​​​开发思路 ​​​​类的属性和方法​​​​代码......
  • 5. Elasticsearch环境
    5.1 环境-简介5.1.1 环境-简介单台Elasticsearch服务器提供服务,往往都有最大的负载能力,超过这个阈值,服务器性能就会大大降低甚至不可用,所以生产环境中,一般都是运行在......
  • ES 查询时提示:all shards failed [type=search_phase_execution_exception]
    我的情况和解决方案这种错误大概率是ES的查询语句语法错误,比如我当时是,时间筛选的条件的格式写错了,导致ES查询时解析错误,从而报了allshardsfailed[type=search_pha......
  • JAVA8-Lambda-(sorted+Comparator)排序
    使用场景:排队的时候按照个子大小排队使用API排序和MySql中的升序降序规则一样。在排序时需要注意的是降序需要用到reversed();publicstaticvoidmain(String[]......
  • 1233. 全球变暖
    https://www.acwing.com/problem/content/1115/第一步,首先要考虑有多少个连通块,可以直接枚举每个点,对每个点进行一次搜索,与这个点连通的点共同构成一个连通块,数量用cn......
  • Elasticsearch启动后访问不了9200的解决方案
    windows系统下​​elasticsearch​​启动成功,访问不成功问题这里用的版本是 然后你去访问​​http://localhost:9200/​​ 访问不了 原因是是因为开启了 ​​ssl​​ ......
  • P3376 【模板】网络最大流(EK)
    #include<iostream>#include<queue>#include<cstring>usingnamespacestd;constlonglongN=5e3+1;longlongh[N],to[N<<1],nt[N<<1],fro......
  • P3387 【模板】缩点
    #include<iostream>#include<queue>#include<vector>usingnamespacestd;constintN=1e4+1;intn,m;vector<int>to[N];intval[N];voidadd......
  • Elasticsearch 同时使用should和must 只有must生效,java代码解决方案
    ES中同时使用should和must导致只有must生效解决方案失效的原因就是must和should在一起使用会不生效,如果全部都是must是不影响的.加入一个字段需要有类似url=aor......