Suppose a sorted array 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
).

Find the minimum element.

You may assume no duplicate exists in the array.

不知道这道题为什么难度是Medium,感觉蛮简单的。

仅仅须要找到第一个大于它后面的数,它后面的数就是旋转排序数组中最小的数。

将返回结果初始化为数组中的第一个元素。这样就能够将结果统一起来。

时间复杂程度是O(N)。

runtime:4ms

class Solution {
public:
int findMin(vector<int>& nums) {
int result=nums[0];
auto iter=nums.begin();
for(;iter!=nums.end()-1;iter++)
{
if(*iter>*(iter+1))
{
result=*(iter+1);
break;
} }
return result;
}
};

然后看了下Discuss,发现了一个使用二分查找思想的代码。漫有意思的,也有分析。以后在碰到排序好的数组进行了一些变形或一些附加说明时注意使用二分查找的思想。时间复杂程度是O(logN)。

链接

In this problem, we have only three cases.

Case 1. The leftmost value is less than the rightmost value in the list: This means that the list is not rotated. e.g> [1 2 3 4 5 6 7 ]

Case 2. The value in the middle of the list is greater than the leftmost and rightmost values in the list. e.g> [ 4 5 6 7 0 1 2 3 ]

Case 3. The value in the middle of the list is less than the leftmost and rightmost values in the list. e.g> [ 5 6 7 0 1 2 3 4 ]

As you see in the examples above, if we have case 1, we just return the leftmost value in the list. If we have case 2, we just move to the right side of the list. If we have case 3 we need to move to the left side of the list.

Following is the code that implements the concept described above.

int findMin(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while(left < right) {
if(nums[left] < nums[right])
return nums[left]; int mid = (left + right)/2;
if(nums[mid] > nums[right])
left = mid + 1;
else
right = mid;
} return nums[left];
}

最新文章

  1. Andriod中textview垂直水平居中及LinearLayout内组件的垂直布局
  2. 3Com Network Supervisor与IBM Tivoli NetView两款网管软件操作视频
  3. C#微信公众号开发 -- (二)验证成为开发者
  4. H3C交换配置PBR最佳实践
  5. 一种H.264高清视频的无参考视频质量评价算法(基于QP和跳过宏块数)
  6. SpringMVC强大的数据绑定(2)——第六章 注解式控制器详解
  7. 通过对DAO层的封装减少数据库操作的代码量
  8. go语言时间比较
  9. 【转载】django 过滤器 、日期格式化参数
  10. Helm - Kubernetes服务编排的利器
  11. 选择性搜索(SS)算法
  12. Balanced Number HDU - 3709 数位dp
  13. GCD 常用API 总结
  14. SQL--结构化的查询语言
  15. oracle定时任务的编写及查看删除
  16. [转]无网络环境,在Windows Server 2008 R2和SQL Server 2008R2环境安装SharePoint2013 RT
  17. Oracle结合Mybatis实现取表TOP 10
  18. TraClus java版实现
  19. CentOS 7运维管理笔记(12)----GUI配置工具Webmin的安装
  20. hive 导出数据到本地

热门文章

  1. 3D 服务器端以向量计算为主的角色位置的算法
  2. c++11的for新用法 (重新练习一下for_each)
  3. ADS的默认连接分析及编译器产生符号解惑
  4. Map集合的四种遍历
  5. iOS - instancetype
  6. backbone showcase
  7. SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-004-消除BEAN自动装配的歧义@QUALIFIER及自定义注解
  8. OA学习笔记-009-岗位管理的CRUD
  9. Android开源项目发现---ViewPager 、Gallery 篇(持续更新)
  10. WordPress get_allowed_mime_types函数(wp-includes/functions.php)存在跨站脚本漏洞