给定一个数组,无重复值,求数组中元素的最小值与次小值
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int [] a=new int[n];
for (int i = 0; i < n; i++) {
a[i]=in.nextInt();
}
int[] mins = minAndTwo(a);
for (int i = 0; i < mins.length; i++) {
System.out.print(mins[i]+" ");
}
}
private static int [] minAndTwo(int [] arr){
int [] res={-1,-1};
if (arr.length==0){
return res;
}
res[0]=arr[0];
if (arr.length==1){
return res;
}
res[1]=arr[1];
if (res[1]<res[0]){
swap(res,0,1);
}
for (int i=2;i<arr.length;i++){
if (arr[i]<res[0]){
res[1]=res[0];
res[0]=arr[i];
}else if (arr[i]<res[1]){
res[1]=arr[i];
}
}
return res;
}
private static void swap(int [] a,int x,int y){
int t=a[x];
a[x]=a[y];
a[y]=t;
}