笔试题算法系列(五)百度2017买帽子

时间限制:1秒

空间限制:32768K

度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同。度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少?
输入描述:
首先输入一个正整数N(N <= 50),接下来输入N个数表示每顶帽子的价格(价格均是正整数,且小于等于1000)
输出描述:
如果存在第三便宜的帽子,请输出这个价格是多少,否则输出-1
输入例子1:
10
10 10 10 10 20 20 30 30 40 40
输出例子1:
30

代码如下:
 1 import java.util.Arrays;
 2 import java.util.Scanner;
 3 public class Main{
 4     public static void main(String[] args){
 5         Scanner sc = new Scanner(System.in);
 6         String[] line;
 7         while(sc.hasNext()){
 8             line = sc.nextLine().split(" ");
 9             int n = Integer.parseInt(line[0]);
10             line = sc.nextLine().split(" ");
11             int[] prices = new int[n];
12             for(int i=0; i<n; i++){
13                 prices[i]=Integer.parseInt(line[i]);
14             }
15             Arrays.sort(prices);
16             int count =1;
17             int max = prices[0];
18             int result = 0;
19             for(int i=0; i<n; i++){
20                 if(prices[i]== max){
21                     continue;
22                 }else{
23                     count++;
24                     max = prices[i];
25                 }
26                 if(count==3){
27                     break;
28                 }
29             }
30             if(count==3){
31                 System.out.println(max);
32             }else{
33                 System.out.println(-1);
34             }
35             
36         }
37         sc.close();
38     } 
39 }
原文地址:https://www.cnblogs.com/haimishasha/p/10638039.html