題目
-
數組異或操作
-
保證文件名唯一
注意這個示例:
思路與算法
- 半個月沒寫博客了,太懶了,不能再拖延了,今天開始全部帶上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)。