百度笔试测试开发暑期实习4.12
第一题
首先需要找出其中出现次数最多的整数,如果出现次数最多的整数不唯一,则找出其中值最大的整数,记为M; 然后再找出其中出现次数最少的整数,如果出现次数最少的整数不唯一,则找出其中值最小的整数,记为N;最后计算M和N的差,即输出(M-N)。
首先需要找出其中出现次数最多的整数,如果出现次数最多的整数不唯一,则找出其中值最大的整数,记为M; 然后再找出其中出现次数最少的整数,如果出现次数最少的整数不唯一,则找出其中值最小的整数,记为N;最后计算M和N的差,即输出(M-N)。
思路:用HashMap
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int[] nums=new int[n];
for(int i=0;i<n;i++){
nums[i]=scan.nextInt();
}
System.out.println(getM(nums)-getN(nums));
scan.close();
}
public static int getM(int[] nums){
HashMap<Integer,Integer> map =new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
int tmp=map.get(nums[i]);
map.put(nums[i],tmp+1);
}else{
map.put(nums[i],1);
}
}
Collection<Integer> count=map.values();
int maxCount=Collections.max(count);
List<Integer> list=new ArrayList<>();
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
if(maxCount==entry.getValue()){
list.add(entry.getKey());
}
}
int maxReal=Integer.MIN_VALUE;
for(int i=0;i<list.size();i++){
if(list.get(i)>maxReal){
maxReal=list.get(i);
}
}
return maxReal;
}
public static int getN(int[] nums){
HashMap<Integer,Integer> map =new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
int tmp=map.get(nums[i]);
map.put(nums[i],tmp+1);
}else{
map.put(nums[i],1);
}
}
Collection<Integer> count=map.values();
int minCount=Collections.min(count);
List<Integer> list=new ArrayList<>();
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
if(minCount==entry.getValue()){
list.add(entry.getKey());
}
}
int minReal=Integer.MAX_VALUE;
for(int i=0;i<list.size();i++){
if(list.get(i)<minReal){
minReal=list.get(i);
}
}
return minReal;
}
} 第二题 n个绳子,每根绳子最多切割一次,最终得到最多根长度相同的绳子,输出长度相同绳子的个数
思路: HashMap得到相同长度最多的绳子,
public class test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int[] nums=new int[n];
for(int i=0;i<n;i++){
nums[i]=scan.nextInt();
}
System.out.println(lines(nums));
scan.close();
}
public static int lines(int[] nums){
HashMap<Integer,Integer> map =new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i])){
map.put(nums[i],map.get(nums[i])+1);
}else{
map.put(nums[i],1);
}
}
int max= Collections.max(map.values());//长度相同的绳子 ,若绳子为2,3,3,5,5 则max=2
Set<Integer> set=new HashSet<>();
for(Map.Entry<Integer,Integer> entry1 : map.entrySet()){
if(entry1.getValue()==max){
set.add(entry1.getKey());//若绳子为2,3,3,5,5 则set为{3,5}
}
}
int M=Collections.min(set);//若绳子为2,3,3,5,5,则M=3
double n=M/2.0; //n=1.5
int sum=2*max; //4 相当于把长为3的绳子分割了
for(int i=0;i<nums.length;i++){
if(M!=nums[i] && nums[i]>=M/2.0){
sum++;
}
}
return sum;
}
} 
