# 旋转数组的最小数字

102人阅读 评论(0)

#### Search Min in Rotated Sorted Array

import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int[] array)
{
if(array == null || array.length <= 0)
try {
throw new Exception("Invalid parameters");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int index1 = 0;
int index2 = array.length - 1;
int indexMid = index1;
while(array[index1] >= array[index2])
{
if(index2 - index1 == 1)
{
indexMid = index2;
break;
}

indexMid = (index1 + index2) / 2;
if(array[indexMid] >= array[index1])
index1 = indexMid;
else if(array[indexMid] <= array[index2])
index2 = indexMid;
}
return array[indexMid];
}
}


#### Search  Min in Rotated Sorted Array 2(when duplicates are allowed)

import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int[] array)
{
if(array == null || array.length <=0)
return 0;
int index1 = 0;
int index2 = array.length - 1;
int indexMid = index1;
while(array[index1] >= array[index2])
{
if(index2 - index1 == 1)
{
indexMid = index2;
break;
}

indexMid = (index1 + index2) / 2;
if(array[index1] == array[index2] ||
array[indexMid] == array[index1] ||
array[indexMid] == array[index2])
return minInOrder(array);

if(array[indexMid] >= array[index1])
index1 = indexMid;
else if(array[indexMid] <= array[index2])
index2 = indexMid;
}
return array[indexMid];
}

private int minInOrder(int[] array)
{
int result = Integer.MAX_VALUE;
for(int i = 0; i < array.length - 1; i++)
{
result = Math.min(result, array[i]);
}
return result;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：64543次
• 积分：1861
• 等级：
• 排名：千里之外
• 原创：125篇
• 转载：6篇
• 译文：0篇
• 评论：4条
评论排行
最新评论