面试题10:旋转数组的最小数字(offer)
来源:互联网 发布:mac qq五笔卸载 编辑:程序博客网 时间:2024/05/01 23:11
题目:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{4,5,1,2,3}是{1,2,3,4,5}的一个旋转,该数组的最小值为1。
思路:
这题跟leetcode里面的一道题目很像,那题是在旋转数组中查找对应的元素。
leetcode 33:Revised Binary Search
还有带重复元素的查找
Search in Rotated Sorted Array II
本题比较简单,只需要找出最小的元素,但是思路是一样的。
当不考虑重复的时候,可以按下面做法:
时间复杂度:O(lgn)
#include <iostream>#include <vector>#include <string>#include <stack>#include <algorithm>using namespace std;int finMin(vector<int> nums){vector<int>::iterator first = nums.begin(), last = nums.end() - 1;if (*first < *last) return *first;while (first < last){if (first == last - 1) return min(*first, *last);vector<int>::iterator mid = (last - first) / 2 + first;if (*mid > *first) first = mid;else last = mid;}return *last;}int main(){int arr[] = { 2, 3, 4, 5, 1 };vector<int> nums(arr, arr + 5);cout << finMin(nums) << endl;return 0;}如果考虑重复情况如下:
时间复杂度:
O(lgn),最坏情况下O(n)
#include <iostream>#include <vector>#include <string>#include <stack>#include <algorithm>using namespace std;int finMin(vector<int> nums){vector<int>::iterator first = nums.begin(), last = nums.end() - 1;if (*first < *last) return *first;while (first < last){if (first == last - 1) return min(*first, *last);vector<int>::iterator mid = (last - first) / 2 + first;if (*mid > *first) first = mid;else if(*mid<*first) last = mid;else last--; //key}return *last;}int main(){int arr[] = { 1, 0, 1, 1, 1 };vector<int> nums(arr, arr + 5);cout << finMin(nums) << endl;return 0;}
0 0
- 面试题10:旋转数组的最小数字(offer)
- 旋转数组的最小数字(剑指offer面试题)
- 【剑指offer】面试题8:旋转数组的最小数字
- 剑指offer面试题8:旋转数组的最小数字
- 剑指Offer:面试题8 :旋转数组的最小数字
- 《剑指offer》面试题8旋转数组的最小数字
- 《剑指Offer》之面试题旋转数组的最小数字
- 《剑指Offer》面试题8:旋转数组的最小数字
- 【剑指offer】 面试题8: 旋转数组的最小数字
- 《剑指Offer》面试题:旋转数组的最小数字
- 剑指offer面试题八:旋转数组的最小数字
- 剑指offer-面试题8:旋转数组的最小数字
- 剑指offer-面试题8.旋转数组的最小数字
- 剑指offer面试题 旋转数组的最小数字
- 剑指offer面试题8:旋转数组的最小数字
- 【剑指offer】面试题8:旋转数组的最小数字
- 剑指offer面试题8:旋转数组的最小数字
- 剑指offer--面试题8: 旋转数组的最小数字
- iOS UIScrollView 没有从顶部开始滑动
- 怎么在MAC OSX机器上运行COCOS2D-X 3.9的CPP-TEST的例子
- Ajax原理
- PHP5下SOAP调用实现过程
- libpng install failed
- 面试题10:旋转数组的最小数字(offer)
- 【UWP通用应用开发】文件选取器、获取文件属性、写入和读取、保存读取和删除应用数据
- iOS9 新增 UIStackView 官方文档翻译
- Struts2重定向传参
- sizeof用法
- [iOS运行错误系列-001]
- oracle 逻辑备份与导入
- Leetcode 240: Search a 2D Matrix II
- phonegap(cordova) 入门 6----iOS 扫码插件,好用,方便,效率高,漂亮,兼容二维码,条形码