TCHS-3-250

Problem Statement

    

After selling goods all day, a salesman would like to determine the most desirable item in his inventory. You are given a String[] items, each element of which represents a single item that was sold during the day. Return the item that was sold the most number of times. In case of a tie, return the item that comes first alphabetically.

Definition

    
Class: BestSeller
Method: findBestSeller
Parameters: String[]
Returns: String
Method signature: String findBestSeller(String[] items)
(be sure your method is public)
    
 

Constraints

- items will contain between 1 and 50 elements, inclusive.
- Each element of items will contain between 1 and 50 characters, inclusive.
- Each element of items will contain only lowercase letters ('a'-'z').

Examples

0)  
    
{"table", "chair", "table", "table", "lamp", "door", "lamp", "table", "chair"}
 
Returns: "table"
 
The salesman sold four "table"s, two "chair"s, two "lamp"s, and one "door". The "table" is his best-selling item.
1)  
    
{"a", "a", "a", "b", "b", "b"}
 
Returns: "a"
 
There is a tie between "a" and "b", "a" is returned, because it comes first alphabetically.
2)  
    
{"icecream", "peanuts", "peanuts", "chocolate", "candy", "chocolate", "icecream", "apple"}
 
Returns: "chocolate"
 
The salesman sold two of each of these items: "icecream", "peanuts", and "chocolate". Since there is a tie, "chocolate" is returned because it comes first alphabetically. "apple" comes even earlier, but only tied items are considered.
3)  
    
{"soul"}
 
Returns: "soul"
 
 
import java.util.Arrays;

public class BestSeller {

	public static String findBestSeller(String[] items) {
		Arrays.sort(items);
		int max, maxi, count = 1;
		max = maxi = 0;
		for (int i = 1; i < items.length; i++) {
			if (!items[i].equals(items[i-1])) {
				if (count > max) {
					max = count;
					maxi = i - 1;
				}
				count = 1;
			} else
				count++;
		}
		return (count > max) ? items[items.length-1] : items[maxi];
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值