20200701:力扣194周周赛上

    技术2022-07-11  86

    力扣194周周赛上

    题目思路与算法代码实现复杂度分析

    题目

    数组异或操作

    保证文件名唯一 注意这个示例:

    思路与算法

    半个月没写博客了,太懒了,不能再拖延了,今天开始全部带上C++和Java的双语言题解。第一题没啥好说的,直接按照题意思路写即可。第二题用map来存下当前字符串出现的次数即可,存好次数,下次找的时候看有没有这个东西,记得如果有这个,需要继续找后面的序数是否也已经在map中,直到找不到为止,此时注意要更新map,具体见代码了。

    代码实现

    数组异或操作 Java实现 class Solution { public int xorOperation(int n, int start) { int res = start; for (int i = 1; i < n;i++) { start += 2; res = res ^ start; } return res; } }

    C++实现

    class Solution { public: int xorOperation(int n, int start) { int res = start; for (int i = 1; i < n;i++) { start += 2; res = res ^ start; } return res; } }; 保证文件名唯一 Java实现 class Solution { public String[] getFolderNames(String[] names) { int len = names.length; // 特殊情况处理 if (len == 0) { return null; } // 初始化结果集字符串 String[] res = new String[len]; // Map<String,Integer> map = new HashMap<>(); for (int i = 0; i < len; i++) { // 如果此前没出现过当前字符串,则直接赋值即可 if (!map.containsKey(names[i])) { res[i] = names[i]; map.put(names[i],1); } else { // 如果出现过,先取出之前出现的次数,再继续判断后面的序号是否出现过 int num = map.get(names[i]); while (map.containsKey(names[i] + "(" + num + ")")) { num++; } // 找到了,直接赋值 res[i] = names[i] + "(" + num + ")"; // 记得更新map map.put(names[i] + "(" + num + ")",1); map.put(names[i],map.get(names[i]) + 1); } } return res; } }

    C++实现:思路一致的,未加注释

    class Solution { public: vector<string> getFolderNames(vector<string>& names) { int n = names.size(); unordered_map<string, int> M; vector<string> res; for(int i = 0; i < n; i++){ string tmp = ""; if(M.find(names[i]) == M.end()){ M[names[i]] = 1; tmp = names[i]; }else{ int k = M[names[i]]; tmp = names[i] + '(' + to_string(k) + ')'; while(M.find(tmp) != M.end()){ k++; tmp = names[i] + '(' + to_string(k) + ')'; } M[names[i]] = k+1; M[tmp] = 1; } res.push_back(tmp); } return res; } };

    复杂度分析

    第二题使用Map时间空间复杂度均为O(N)。
    Processed: 0.013, SQL: 9