# 剑指 Offer 03. 数组中重复的数字

int main() { | |
map<int, int> mp; | |
cout << mp[1] << endl; // 输出 0,同时将 & lt;1,0 > 插入了 | |
if(mp.find(1) == mp.end()) { | |
cout << "not find" << endl; | |
}else{ | |
cout << "find" << endl; // 输出这个 | |
} | |
if(mp.find(2) == mp.end()) { | |
cout << "not find" << endl; // 输出这个 | |
}else{ | |
cout << "find" << endl; | |
} | |
return 0; | |
} |
class Solution { | |
public: | |
int findRepeatNumber(vector<int>& nums) { | |
map<int, int> mp; | |
mp.find(2); | |
mp.end() | |
for(int num: nums){ | |
if(mp[num] == 0){ | |
mp[num] = 1; | |
}else{ | |
return num; | |
} | |
} | |
} | |
}; |


class Solution { | |
public: | |
int findRepeatNumber(vector<int>& nums) { | |
int i = 0; | |
while(i < nums.size()) { | |
if(nums[i] == i) { | |
i++; | |
continue; | |
} | |
if(nums[nums[i]] == nums[i]) | |
return nums[i]; | |
swap(nums[i],nums[nums[i]]); | |
} | |
return -1; | |
} | |
}; |
# 剑指 Offer 04. 二维数组中的查找

class Solution { | |
public: | |
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) { | |
if(matrix.size()==0 || matrix[0].size() == 0){ | |
return false; | |
} | |
int i_length = matrix.size(), j_length = matrix[0].size(); | |
int i = 0, j = j_length - 1; | |
bool res = false; | |
while(i < i_length && j >= 0){ | |
int cur = matrix[i][j]; | |
if(cur == target) { | |
res = true; | |
break; | |
}else if(cur > target){ | |
j--; | |
}else if(cur < target){ | |
i++; | |
} | |
} | |
return res; | |
} | |
}; |
# 剑指 Offer 50. 第一个只出现一次的字符
unordered_map 并不是按照插入的顺序排序的

class Solution { | |
public: | |
char firstUniqChar(string s) { | |
map<char, int> mp; | |
for(char ch: s){ | |
if(mp[ch] == 0){ | |
mp[ch] = 1; | |
}else{ | |
mp[ch] += 1; | |
} | |
} | |
char res = ' '; | |
for(char ch: s){ | |
if(mp[ch] == 1){ | |
res = ch; | |
break; | |
} | |
} | |
return res; | |
} | |
}; |