【剑指offer】旋转递增数组的最小数字
2016-09-03 22:25
423 查看
思路:利用二叉查找原理,定义mid ,before 和behind三个标签
array [mid]>array[before]时,before=mid;
array[mid]<array[behind]时,end=mid
public class MinNumberInRoastedArray {
public static void main(String[] args){
int[] array={1,1,0,1};
int result=minNumberInRoastedArray(array);
System.out.println(result);
}
private static int minNumberInRoastedArray(int[] array) {
// TODO Auto-generated method stub
if(array==null||array.length==0)
throw new RuntimeException("invalid array");
int before=0;
int behind=array.length-1;
int result_idx=0;
if(array[before]<array[behind])
result_idx=before;
else if(array[before]>array[behind]){
int mid=(before+behind)/2;
while(before!=behind-1){
mid=(before+behind)/2;
if(array[mid]>array[before])
before=mid;
else if(array[mid]<array[behind]){
behind=mid;
}
}
result_idx=behind;
}
else if(array[before]==array[behind]){
if(array.length==1) result_idx=before;
else{
while(array[before]>=array[behind]){
before++;
}
result_idx=before;
}
}
return array[result_idx];
}
}
array [mid]>array[before]时,before=mid;
array[mid]<array[behind]时,end=mid
public class MinNumberInRoastedArray {
public static void main(String[] args){
int[] array={1,1,0,1};
int result=minNumberInRoastedArray(array);
System.out.println(result);
}
private static int minNumberInRoastedArray(int[] array) {
// TODO Auto-generated method stub
if(array==null||array.length==0)
throw new RuntimeException("invalid array");
int before=0;
int behind=array.length-1;
int result_idx=0;
if(array[before]<array[behind])
result_idx=before;
else if(array[before]>array[behind]){
int mid=(before+behind)/2;
while(before!=behind-1){
mid=(before+behind)/2;
if(array[mid]>array[before])
before=mid;
else if(array[mid]<array[behind]){
behind=mid;
}
}
result_idx=behind;
}
else if(array[before]==array[behind]){
if(array.length==1) result_idx=before;
else{
while(array[before]>=array[behind]){
before++;
}
result_idx=before;
}
}
return array[result_idx];
}
}
相关文章推荐
- 剑指offer面试题8:旋转数组的最小数字
- leetcode之Search in Rotated Sorted Array,剑指offer之旋转数组的最小数字
- 【剑指Offer面试编程题】题目1386:旋转数组的最小数字--九度OJ
- [剑指Offer]10.旋转数组的最小数字
- 剑指offer 8 - 旋转数组的最小数字
- 【剑指offer】旋转数组的最小数字
- 剑指offer:08 旋转数组的最小数字
- [剑指offer][面试题08]求旋转数组的最小数字
- 剑指Offer之 - 旋转数组的最小数字
- 剑指offer-8 旋转数组的最小数字
- 剑指offer--旋转数组的最小数字
- 剑指offer--旋转数组的最小数字
- 剑指offer源码-旋转数组的最小数字
- 【九度OJ1386】|【剑指offer8】旋转数组的最小数字
- 剑指Offer旋转数组中的最小数字
- 【剑指Offer面试题】 九度OJ1386:旋转数组的最小数字
- 剑指Offer之旋转数组的最小数字
- 剑指offer-08旋转数组的最小数字
- 【剑指offer】面试题八:旋转数组的最小数字
- 剑指offer面八_旋转数组的最小数字