百度笔试- 买帽子

时间限制: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--;
		}
	}
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值