【笔试记录】2020.8.26 深信服笔试(最小移动次数使数组元素相等、字符串连续变换)


题目类型:不定向选择、填空题、编程题

1、魔法棒

题目

在这里插入图片描述

思路

  • 每次的操作:指定一棵树高度不变,其余树高度加1
  • 最终目标:所有树的高度相同
  • 那其实这个操作就等用于指定一棵树高度减1,其余树高度不变,最终目标是所有树的高度都减到最矮树。那就记录高度最小值,最终要求的就是其余树高度和最小值的差的总和。
  • 我下面的代码ac,现在感觉其实不用排序,输入的时候记录minvalue就可以了
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <map>
#include "limits.h"
#include "math.h"
using namespace std;

int main(int argc, const char * argv[]) {
    long long n;
    cin >> n; //n棵树
    vector<long long> nums(n);
    long long height;
    for(long long  i=0; i<n; i++){
        cin >> height;
        nums[i] = height;
    }
    sort(nums.begin(), nums.end());
    long long minvalue = nums[0];
    long long i=0;
    for(; i<n; i++){
        if( nums[i] != minvalue )
            break;
    }
    long long  count = 0;
    for(; i<n; i++){
        count += nums[i] - minvalue;
    }

    cout << count << endl;

    return 0;
}

leetcode原题

leetcode 453. 最小移动次数使数组元素相等

2、字符串连续变换

题目

在这里插入图片描述

思路

这道题有个大坑!!题目要求是模拟每一步操作,就是每输入一对变换对,就进行一次操作,输出最后一次的结果,那么对于先输入(2,3),再输入了(0,2)这种情况其实是不用考虑了!一旦考虑了,而且没处理好的话,输入很有可能就会形成环,然后就一直卡在超时…

  • 用hashmap存储数字[0-9]对应的变换值,默认变换值是自己
  • 每次输入变换对(a,b)时,直接覆盖a的变换值为b;并且判断当前有没有哪个数字的变换是a,如果有那就更新为b。最后对输入字符串的字符逐个变换即可
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <map>
#include <unordered_map>
#include "limits.h"
#include "math.h"
using namespace std;

int main(int argc, const char * argv[]) {
    string str;
    int n;
    cin >> str >> n;
    //先初始化
    unordered_map<char,char> unmap;
    for(int i=0; i<=9; i++){
        unmap[(char)(i+'0')] = (char)(i+'0');
    }
    //输入并建立联系
    char a,b;
    for(int i=0;i<n; i++){
        cin >> a >> b;
        unmap[a] = b;
        //已有2,3,输入0,2 这里不用考虑啊!!因为是模拟每一步!!操作顺序不能忽略...
//        char c = b;
//        while( unmap[c] != c ){ //就算要考虑,这种写法也会超时,万一出现环呢...
//            unmap[a] = unmap[c];
//            c = unmap[c];
//        }
        //已有0,2,输入2,3
        for(int j=0 ;j<=9; j++){
            if( unmap[(char)(j+'0')] == a ){
                unmap[(char)(j+'0')] = b;
            }
        }
    }
    for(int i=0; i<str.length(); i++){
        str[i] = unmap[str[i] ];
    }
    cout << str << endl;
    return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值