百度2017年春招程式設計筆試題
阿新 • • 發佈:2019-01-30
[程式設計題] 買帽子
時間限制:1秒
空間限制:32768K
度度熊想去商場買一頂帽子,商場裡有N頂帽子,有些帽子的價格可能相同。度度熊想買一頂價格第三便宜的帽子,問第三便宜的帽子價格是多少?
輸入描述:
首先輸入一個正整數N(N <= 50),接下來輸入N個數表示每頂帽子的價格(價格均是正整數,且小於等於1000)
輸出描述:
如果存在第三便宜的帽子,請輸出這個價格是多少,否則輸出-1
輸入例子:
10
10 10 10 10 20 20 30 30 40 40
輸出例子:
30
解題:
import java.util.Scanner; import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int N = scan.nextInt(); int count=0; int i; int j=0; int[] array = new int[N]; for(i=0;i<N;i++) { array[i]=scan.nextInt(); } for (i = 0; i < array.length; i++) { for (j = i; j < array.length; j++) { if (array[i] > array[j]) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } } if(N<=2) { System.out.println(-1); return; } for(i=0;i<N-1;i++) { if(array[i]<array[i+1]) { count++; if(count ==2 ) { System.out.println(array[i+1]); } } } if(count<2) { System.out.println(-1); } } }