欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

(牛客网)华为机试(三)

程序员文章站 2022-06-17 18:46:32
...

(牛客网)华为机试题集解答

HJ102 字符统计

(牛客网)华为机试(三)(牛客网)华为机试(三)

思路分析:

看到这道题目我们的第一想法就是开两个数组来分别存每个字符出现的次数,和对应次数上的字符,让字符次数相同的位置再将对应的字符进行ASII码来比较一下大小,想法听起来很棒,但是具体实现的时候就发现逻辑上越写越复杂,所以我决定索性用map来直接操作,将字符和次数直接作为一对捆绑的关系来处理,开始遍历一次str使用map保存每个char出现的次数,以char为键,int为值,然后遍历一次map使用treemap保存每个char的次数,以int为键,char为值,最后遍历treemap将每个char保存到stringbuffer中,最后reverse反转输出,这样的处理方式也让我学到HashMap的用法。

import java.util.*;
public class Main{
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
            String words = scanner.next();
            Map<Character,Integer> map = new HashMap<Character,Integer>(127);
            for(int i=0;i<words.length();i++){
                char word = words.charAt(i);
                if(!map.containsKey(word)){
                    map.put(word,1);
                }
                else{
                    map.put(word,map.get(word)+1);
                }
            }
            Map<Integer, Character> treeMap = new TreeMap<Integer,Character>();
            for(char word:map.keySet()){
                treeMap.put(map.get(word)*128+128-word,word);
            }
            StringBuilder stringbuilder = new StringBuilder();
            for(int j:treeMap.keySet()){
                stringbuilder.append(treeMap.get(j));
            }
            System.out.println(stringbuilder.reverse().toString());
        }
    }
}
HJ101 输入整型数组和排序标识,对其元素按照升序或降序进行排列

(牛客网)华为机试(三)(牛客网)华为机试(三)

思路分析

就简单的一个升序与降序算法,只是要对输入的算法的执行进行一个分类,用一个flag作为分类的表示符号,如果输入1就降序,如果输入0就升序。具体的降序和升序算法可以使用冒泡,快排,堆等等。感觉这道题就是检验一下大家的OJ输入输出是否熟练。顺便吹个水:python做这种简单题天下无敌,因为代码少呀!!!!

while True:
    try:
        a,b,c=input(),map(int,input().split()),input()
        print(" ".join(map(str,sorted(b))) if c=="0" else " ".join(map(str,sorted(b,reverse=True))))
    except:break

HJ101等差数列(大水题)

(牛客网)华为机试(三)

思路分析

初中数学题,数列前n项和=[(首项+尾项)*项数/2]按公式直接输出就好了

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        cout<<n*2+(n-1)*n*3/2<<endl;
    }
}

HJ100 自守数

(牛客网)华为机试(三)(牛客网)华为机试(三)

思路分析

这种XX数的题目基本都是查找,遍历一边数字,然后加个判断条件,然后根据题目要求是输出满足条件的数还是个数返回函数结果就好了。

import java.util.Scanner;
public class Main{
    public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
            int n = scanner.nextInt();
            int count=0;
            for(int i=0;i<n;i++){
                if(String.valueOf(i*i).substring(String.valueOf(i*i).length()-String.valueOf(i).length()).equals(String.valueOf(i)))
                count++;
            }
            System.out.println(count);
        }
    }
}

HJ99自动售货系统

(牛客网)华为机试(三)(牛客网)华为机试(三)(牛客网)华为机试(三)(牛客网)华为机试(三)(牛客网)华为机试(三)(牛客网)华为机试(三)(牛客网)华为机试(三)(牛客网)华为机试(三)

思路分析:(无限if … else if处理)

这道题目纯粹是为了恶心人的存在,第一次看题就失去做他的意愿,“又臭又长”,慢慢忍着兴致看完题目发现这题目就按着要求输入数字然后进行判断处理结束后输出结果就好了,唯一需要注意的就是输出结果的格式。

while True:
    try:
        priceGoods = {'A1': 2, 'A2': 3, 'A3': 4, 'A4': 5, 'A5': 8, 'A6': 6}
        numGoods = {'A1': 0, 'A2': 0, 'A3': 0, 'A4': 0, 'A5': 0, 'A6': 0}
        priceMoney = [1, 2, 5, 10]
        numMoney = [0] * 4
        balance = 0
 
        #首先定义了输出函数
        def printGoods(priceGoods, numGoods):
            numGoodsSorted = sorted((sorted(numGoods.items(), key=lambda x: x[0])), key=lambda item: item[1],
                                    reverse=True)
            for i in numGoodsSorted:
                print(i[0] + ' ' + str(priceGoods[i[0]]) + ' ' + str(i[1]))
 
        #定义钱数输出函数
        def printMoney(numMoney):
            print('1 yuan coin number=%d' % (numMoney[0]))
            print('2 yuan coin number=%d' % (numMoney[1]))
            print('5 yuan coin number=%d' % (numMoney[2]))
            print('10 yuan coin number=%d' % (numMoney[3]))
 
 
        string = input().rstrip(';').split(';')#这里如果不rstrip,那么最后分割之后就会有一个空字符在最后
        for i in string:
            cmds = i.split()
            if cmds[0] == 'r':
                '''系统初始化'''
                for i in range(6):
                    numGoods['A' + str(i + 1)] += int(cmds[1].split('-')[i])
                for i in range(4):
                    numMoney[i] += int(cmds[2].split('-')[i])
                print("S001:Initialization is successful")
            elif cmds[0] == 'p':
                cash = int(cmds[1])
                if cash not in priceMoney:
                    print("E002:Denomination error")
                elif cash in (5, 10) and cash > (numMoney[0] + numMoney[1] * 2):
                    print("E003:Change is not enough, pay fail")
                elif cash > 10:
                    print("E004:Pay the balance is beyond the scope biggest")
                elif numGoods['A1'] == numGoods['A2'] == numGoods['A3'] == numGoods['A4'] == numGoods['A5'] == numGoods[
                    'A6'] == 0:
                    print("E005:All the goods sold out")
                else:
                    numMoney[priceMoney.index(cash)] += 1
                    balance += cash
                    print("S002:Pay success,balance=%d" % (balance))
            elif cmds[0] == 'b':
                goods = cmds[1]
                if goods not in numGoods:
                    print("E006:Goods does not exist")
                elif numGoods[goods] == 0:
                    print("E007:The goods sold out")
                elif balance < priceGoods[goods]:
                    print("E008:Lack of balance")
                else:
                    balance -= priceGoods[goods]
                    print("S003:Buy success,balance=%d" % (balance))
            elif cmds[0] == 'c':
                '''退币'''
                if balance == 0:
                    print("E009:Work failure", end='')
                elif balance > 0:
                    numCall = [0] * 4
                    for i in range(-1, -5, -1):
                        numCall[i] += min(balance // priceMoney[i], priceMoney[i])
                        numMoney[i] -= numCall[i]
                        balance -= numCall[i] * priceMoney[i]
                        if balance == 0:
                            break
                    balance = 0
                    print("1 yuan coin number=%d" % (numCall[0]))
                    print("2 yuan coin number=%d" % (numCall[1]))
                    print("5 yuan coin number=%d" % (numCall[2]))
                    print("10 yuan coin number=%d" % (numCall[3]))
            elif cmds[0] == 'q':
                if cmds[1] == '0':
                    printGoods(priceGoods, numGoods)
                elif cmds[1] == '1':
                    printMoney(numMoney)
            else:
                print("E010:Parameter error", end='')
    except:
        break

欢乐的时光总是短暂的,让我们下一次再见!!!

good good studym,day day up! (study hard, improve every day)

预知后事,请听下回分解!!!!