百度笔试- 买帽子
時間限制:1秒
空間限制:32768K
度度熊想去商場買一頂帽子,商場里有N頂帽子,有些帽子的價格可能相同。度度熊想買一頂價格第三便宜的帽子,問第三便宜的帽子價格是多少??輸入描述:
首先輸入一個正整數N(N <= 50),接下來輸入N個數表示每頂帽子的價格(價格均是正整數,且小于等于1000)輸出描述:
如果存在第三便宜的帽子,請輸出這個價格是多少,否則輸出-1輸入例子:
10 10 10 10 10 20 20 30 30 40 40輸出例子:
30此題比較簡單,先將數組進行排序,我是用的冒泡排序,然后再遍歷排好序的數組,當出現三個不一樣的價格時,返回第三個價格,即所求的第三便宜的價格,?沒有找到,返回-1;
代碼如下: package baidu;import java.util.Scanner;public class test1 {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int[] p = new int[n];int i = 0;while (sc.hasNext()) {for (; i < n; i++) {p[i] = sc.nextInt();}System.out.println(help(p));}sc.close();}public static int help(int[] a) {if (a == null || a.length < 3)return -1;int n = a.length;bubbleSort(a, n);int i = 0;int j = 0;int res = 0;int count = 1;for (; i < n; i++) {for (j = i + 1; j < n && i < n; j++) {if (a[j] != a[i]) {count++;if (count == 3) {res = j;return a[res];}i = j;}}}return -1;}public static void bubbleSort(int[] a, int n) {int i = n - 1;int j;int temp;while (i > 0) {for (j = 0; j < n - 1; ++j) {if (a[j] > a[j + 1]) { // 前一個數比后一個數大,則交換兩個數的位子temp = a[j + 1];a[j + 1] = a[j];a[j] = temp;}}i--;}} }
總結
- 上一篇: 7-2 换硬币 (20分)
- 下一篇: 【青岛seo基础知识教程】SEO优化:1