百度笔试- 买帽子

来源:互联网 发布:cgi程序获取开发板数据 编辑:程序博客网 时间:2024/04/28 04:19

时间限制:1秒

空间限制:32768K

度度熊想去商场买一顶帽子,商场里有N顶帽子,有些帽子的价格可能相同。度度熊想买一顶价格第三便宜的帽子,问第三便宜的帽子价格是多少? 
输入描述:
首先输入一个正整数N(N <= 50),接下来输入N个数表示每顶帽子的价格(价格均是正整数,且小于等于1000)


输出描述:
如果存在第三便宜的帽子,请输出这个价格是多少,否则输出-1

输入例子:
1010 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--;}}}


0 0
原创粉丝点击