您的位置:首页 > 其它

寻找旋转数组中最小的数I和II

2017-06-06 19:48 381 查看
I:假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。

你需要找到其中最小的元素。

你可以假设数组中不存在重复的元素。

 注意事项

You may assume no duplicate exists in the array.

样例

给出[4,5,6,7,0,1,2]  返回 0

II:假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。

你需要找到其中最小的元素。

数组中可能存在重复的元素。

 注意事项

The array may contain duplicates.

样例

给出[4,4,5,6,7,0,1,2]  返回 0

import java.util.Scanner;

/**
* 假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。
你需要找到其中最小的元素。
你可以假设数组中不存在重复的元素。
注意事项
You may assume no duplicate exists in the array.
样例
给出[4,5,6,7,0,1,2] 返回 0
*
* @author Dell
*
*/
public class Test159 {
public static int findMin(int[] nums)
{ if(nums==null)
return -1;
int result=nums[0];
int i;
for(i=0;i<nums.length-1;i++)
{
if(nums[i+1]>nums[i])
continue;
else
result=nums[i+1];
}

return result;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int
;
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}

System.out.println(findMin(a));

}

}


import java.util.Scanner;

/**
* 假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。
你需要找到其中最小的元素。
数组中可能存在重复的元素。
注意事项
The array may contain duplicates.
样例
给出[4,4,5,6,7,0,1,2] 返回 0
*
* @author Dell
*
*/
public class Test160 {
public static int findMin(int[] nums)
{ if(nums==null)
return -1;
int result=nums[0];
int i;
for(i=0;i<nums.length-1;i++)
{
if(nums[i+1]>=nums[i])
continue;
else
result=nums[i+1];
}
return result;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int
;
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}

System.out.println(findMin(a));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode