1. Two Sum https://leetcode.com/problems/two-sum/description/

不使用额外空间需要n*n的复杂度

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i=;i<nums.size()-;i++){
for(int j=i+;j<nums.size();j++){
if(nums[i] + nums[j] == target){
vector<int> result;
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return vector<int>();
}
};

需要关注使用hash_table来实现的方法

class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> m;
vector<int> result;
for(int i=;i<nums.size();i++){
auto r = m.find(target-nums[i]);
if(r != m.end()){
result.push_back((*r).second);
result.push_back(i);
return result;
}else{
m[nums[i]] = i;
}
}
return result;
}
};

3. Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

使用hash表来存放每一个字符之前出现过的最右位置,代码中用pos来保存不重复子串的开头,i向前遍历,如果发现i在之前出现过,并且出现的位置在pos之后,则将pos置位当前i之前出现的位置

class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<int,int> m;
int pos = -;
int result = ;
for(int i=;i<s.size();i++){
auto r = m.find(s[i]);
if(r!=m.end() && (*r).second>pos)
pos = (*r).second;
m[s[i]] = i;
result = max(result,i-pos);
}
return result;
}
};

双指针遍历,两个指针指向的元素相等,但是两指针之间的元素不重复,pos2-pos1表示长度

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int pos1 = -;
int result = ;
for(int i=;i<s.size();i++){
for(int j=pos1+;j<i;j++){
if(s[j] == s[i])
pos1 = j;
}
result = max(result,i-pos1);
}
return result;
}
};

36. Valid Sudoku https://leetcode.com/problems/valid-sudoku/description/

class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_multimap<int, pair<int, int>> hash;
if (board.size() == ) return false;
for (int i = ; i<board.size(); i++) {
for (int j = ; j<board[].size(); j++) {
if (board[i][j] == '.') continue;
auto range = hash.equal_range(board[i][j]);
for (auto v = range.first; v != range.second; v++) {
int currenti = (*v).second.first;
int currentj = (*v).second.second;
if (currenti == i || currentj == j || (currenti / == i / && currentj / == j / ))
return false;
}
hash.insert(pair<int, pair<int, int>>(board[i][j], pair<int, int>(i, j)));
}
}
return true;
}
};

熟悉unordered_multimap的使用

49. Group Anagrams https://leetcode.com/problems/group-anagrams/description/

vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> m;
for (int i = ; i<strs.size(); i++) {
string current = strs[i];
sort(current.begin(), current.end());
auto r = m.find(current);
if (r != m.end()) {
r->second.push_back(strs[i]);
}
else {
vector<string> v;
v.push_back(strs[i]);
m[current] = v;
}
} vector<vector<string>> result;
for (auto i = m.begin(); i != m.end(); i++) {
result.push_back(i->second);
}
return result;
}

使用map很容易实现,题目也没有要求空间复杂度

187. Repeated DNA Sequences https://leetcode.com/problems/repeated-dna-sequences/description/

class Solution {
public:
vector<string> findRepeatedDnaSequences(string s) {
vector<string> result;
map<string,int> temp;
int pos = ;
while (pos+ <= s.size()) {
string s_temp = s.substr(pos++,);
temp[s_temp]++;
if (temp[s_temp] == )
result.emplace_back(s_temp);
}
return result;
}
};

这题使用string作为索引还是太复杂了,可以用两个位来表示一个核苷酸,则使用一个int就可以保存一个DNA序列,比较次数可以缩减很多

202. Happy Number https://leetcode.com/problems/happy-number/description/

class Solution {
public:
bool isHappy(int n) {
set<int> s;
s.insert(n);
int next = ;
while (n != ) {
while (n>) {
int i = n % ;
n = n / ;
next = next + i*i;
}
if (s.find(next) != s.end())
return false;
else
s.insert(next);
n = next;
next = ;
}
return true;
}
};

用hash来判断循环

204. Count Primes https://leetcode.com/problems/count-primes/description/

class Solution {
public: bool is_prime(int n){
if(n<=) return false;
int sqr=sqrt(n);
for(int i=;i<=sqr;i++)
if(n%i==)
return false;
return true;
} int countPrimes(int n) {
int result = ;
for(int i=;i<n;i++){
if(is_prime(i))
result++;
}
return result;
}
};

记住直接判断一个是不是质数的方法,不能平方,会溢出

class Solution {
public:
int countPrimes(int n) {
bool* isPrime = new bool[n];
for(int i = ; i < n; i++){
isPrime[i] = true;
}
for(int i = ; i*i < n; i++){
if (!isPrime[i])
continue;
for(int j = i * i; j < n; j += i){
isPrime[j] = false;
}
}
int count = ;
for (int i = ; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
};

205. Isomorphic Strings https://leetcode.com/problems/isomorphic-strings/description/

class Solution {
public:
bool isIsomorphic(string s, string t) {
map<char,char> m1;
map<char,char> m2;
for(int i=;i<s.size();i++){
if(m1.find(s[i])==m1.end()&&m2.find(t[i])==m2.end()){
m1[s[i]] = t[i];
m2[t[i]] = s[i];
}else{
if(m1[s[i]]!=t[i]||m2[t[i]]!=s[i])
return false;
}
}
return true;
}
};

217. Contains Duplicate https://leetcode.com/problems/contains-duplicate/description/

class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;
for(int i=;i<nums.size();i++){
auto r = s.find(nums[i]);
if(r != s.end())
return true;
else
s.insert(nums[i]);
}
return false;
}
};

219. Contains Duplicate II https://leetcode.com/problems/contains-duplicate-ii/description/

class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int,int> map;
for(int i=;i<nums.size();i++){
if(map[nums[i]] != && (i-map[nums[i]]+)<=k)
return true;
else
map[nums[i]] = i+;
}
return false;
}
};

242. Valid Anagram https://leetcode.com/problems/valid-anagram/description/

排序

class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(),s.end());
sort(t.begin(),t.end());
return s==t;
}
};

hash

class Solution {
public:
bool isAnagram(string s, string t) {
map<int,int> m;
if(s.size()!=t.size()) return false;
for(int i=;i<s.size();i++){
m[s[i]]++;
m[t[i]]--;
}
for(auto i=m.begin();i!=m.end();i++){
if(i->second != )
return false;
}
return true;
}
};

274. H-Index https://leetcode.com/problems/h-index/description/

class Solution {
public:
int hIndex(vector<int>& citations) {
if(citations.size()==) return ;
vector<int> v(*max_element(citations.begin(),citations.end())+,);
for(int i=;i<citations.size();i++){
v[citations[i]]++;
}
int last = ;
for(int i=v.size()-;i>=;i--){
v[i] = v[i]+last;
last = v[i];
if(v[i]>=i)
return i;
}
return ;
}
};

290. Word Pattern https://leetcode.com/problems/word-pattern/description/

bool wordPattern(string pattern, string str) {
map<char, string> m1;
map<string, char> m2;
int firstpos = ;
int i = ;
for (; i<pattern.size() && firstpos<str.size(); i++) {
int nextspace = firstpos;
while (nextspace<str.size() && str[nextspace] != ' ') {
nextspace++;
}
string currents = str.substr(firstpos, nextspace - firstpos);
//判断
if (m1.find(pattern[i]) != m1.end() || m2.find(currents) != m2.end()) {
if (m1[pattern[i]] != currents || m2[currents] != pattern[i])
return false;
}
else {
m1[pattern[i]] = currents;
m2[currents] = pattern[i];
}
firstpos = nextspace + ;
}
if (i >= pattern.size() && firstpos >= str.size())
return true;
else
return false;
}

边界条件必须掌握好,长度必须一样,各个对于字符的对于关系处理方式参考205

299. Bulls and Cows https://leetcode.com/problems/bulls-and-cows/description/

string getHint(string secret, string guess) {
int num1 = ;
int num2 = ;
map<char, int> m1;
map<char, int> m2;
for (int i = ; i<min(secret.size(), guess.size()); i++) {
if (secret[i] == guess[i])
num1++;
else {
m1[secret[i]]++;
m2[guess[i]]++;
if (m1[guess[i]]!=) {
m2[guess[i]]--;
m1[guess[i]]--;
num2++;
}
if (m2[secret[i]]!= ) {
m1[secret[i]]--;
m2[secret[i]]--;
num2++;
}
}
}
return to_string(num1) + "A" + to_string(num2) + "B";
}

347. Top K Frequent Elements https://leetcode.com/problems/top-k-frequent-elements/description/

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
for (int num : nums)
++m[num]; vector<vector<int>> buckets(nums.size() + );
for (auto p : m)
buckets[p.second].push_back(p.first); vector<int> ans;
for (int i = buckets.size() - ; i >= && ans.size() < k; --i) {
for (int num : buckets[i]) {
ans.push_back(num);
if (ans.size() == k)
break;
}
}
return ans;
}
};

用多种方法来实现,熟悉c++中各种容器的接口

349. Intersection of Two Arrays https://leetcode.com/problems/intersection-of-two-arrays/description/

class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int,int> hash;
for(int i=;i<nums1.size();i++){
hash[nums1[i]]++;
}
vector<int> result;
for(int i=;i<nums2.size();i++){
if(hash[nums2[i]] != ){
result.push_back(nums2[i]);
hash[nums2[i]] = ;
}
}
return result;
}
};

350. Intersection of Two Arrays II https://leetcode.com/problems/intersection-of-two-arrays-ii/description/

class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int,int> hash;
for(int i=;i<nums1.size();i++){
hash[nums1[i]]++;
}
vector<int> result;
for(int i=;i<nums2.size();i++){
if(hash[nums2[i]]!=){
result.push_back(nums2[i]);
hash[nums2[i]]--;
}
}
return result;
}
};

355. Design Twitter https://leetcode.com/problems/design-twitter/description/

380. Insert Delete GetRandom O(1) https://leetcode.com/problems/insert-delete-getrandom-o1/description/

387. First Unique Character in a String https://leetcode.com/problems/first-unique-character-in-a-string/description/

优化,最后遍历char数组而不是s来找出不重复字符

389. Find the Difference https://leetcode.com/problems/find-the-difference/description/

class Solution {
public:
char findTheDifference(string s, string t) {
unordered_map<char,int> hash;
for(int i=;i<t.size();i++){
hash[t[i]]++;
}
for(int i=;i<s.size();i++){
hash[s[i]]--;
}
for(auto i=hash.begin();i!=hash.end();i++){
if(i->second == )
return i->first;
}
return 'A';
}
};

409. Longest Palindrome https://leetcode.com/problems/longest-palindrome/description/

class Solution {
public:
int longestPalindrome(string s) {
int result = ;
unordered_map<char,int> hash;
for(int i=;i<s.size();i++){
if(hash[s[i]]==){
hash[s[i]] = ;
result = result + ;
}else
hash[s[i]]++;
}
if(s.size()>result)
result++;
return result;
}
};

438. Find All Anagrams in a String https://leetcode.com/problems/find-all-anagrams-in-a-string/description/

class Solution {
public:
vector<int> findAnagrams(string s, string p) {
int n = s.length();
int l = p.length();
vector<int> ans;
vector<int> vp(, );
vector<int> vs(, );
for (char c : p) ++vp[c - 'a'];
for (int i = ; i < n; ++i) {
if (i >= l) --vs[s[i - l] - 'a'];
++vs[s[i] - 'a'];
if (vs == vp) ans.push_back(i + - l);
}
return ans;
}
};

447. Number of Boomerangs https://leetcode.com/problems/number-of-boomerangs/description/

class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
int res = ; // iterate over all the points
for (int i = ; i < points.size(); ++i) { unordered_map<long, int> group(points.size()); // iterate over all points other than points[i]
for (int j = ; j < points.size(); ++j) { if (j == i) continue; int dy = points[i].second - points[j].second;
int dx = points[i].first - points[j].first; // compute squared euclidean distance from points[i]
int key = dy * dy;
key += dx * dx; // accumulate # of such "j"s that are "key" distance from "i"
++group[key];
} for (auto& p : group) {
if (p.second > ) {
/*
* for all the groups of points,
* number of ways to select 2 from n =
* nP2 = n!/(n - 2)! = n * (n - 1)
*/
res += p.second * (p.second - );
}
}
} return res;
}
};

451. Sort Characters By Frequency https://leetcode.com/problems/sort-characters-by-frequency/description/

class Solution {
public:
string frequencySort(string s) {
unordered_map<char,int> hash;
for(int i=;i<s.size();i++){
hash[s[i]]++;
}
sort(s.begin(),s.end(),[&hash](char& a, char& b){
if(hash[a]!=hash[b])
return hash[a]>hash[b];
else
return a<b;
});
return s;
}
};

string的排序比vector<char>的慢

454. 4Sum II https://leetcode.com/problems/4sum-ii/description/

class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
unordered_map<int, int> abSum;
for(auto a : A) {
for(auto b : B) {
++abSum[a+b];
}
}
int count = ;
for(auto c : C) {
for(auto d : D) {
auto it = abSum.find( - c - d);
if(it != abSum.end()) {
count += it->second;
}
}
}
return count;
}
};

463. Island Perimeter https://leetcode.com/problems/island-perimeter/description/

class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
if(grid.size()==) return ;
int result = ;
for(int i=;i<grid.size();i++){
for(int j=;j<grid[].size();j++){
if(grid[i][j] == ){
if(i-< || grid[i-][j]==){
++result;
}
if(j-< || grid[i][j-]==){
++result;
}
if(i+==grid.size() || grid[i+][j]==){
++result;
}
if(j+==grid[].size() || grid[i][j+]==){
++result;
}
}
}
}
return result;
}
};

500. Keyboard Row https://leetcode.com/problems/keyboard-row/description/

class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<int> dict();
vector<string> rows = {"QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"};
for (int i = ; i < rows.size(); i++) {
for (auto c : rows[i]) dict[c-'A'] = << i;
}
vector<string> res;
for (auto w : words) {
int r = ;
for (char c : w) {
r &= dict[toupper(c)-'A'];
if (r == ) break;
}
if (r) res.push_back(w);
}
return res;
}
};

复习题

1

3

36

204

205

290

347

355

380

387

438

447

451、提高效率

LeetCode哈希表的更多相关文章

  1. leetcode.哈希表.594最长和谐子序列-Java

    1. 具体题目: 和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1.现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度. 示例 1: 输入: [1,3,2,2,5 ...

  2. LeetCode 哈希表 380. 常数时间插入、删除和获取随机元素(设计数据结构 List HashMap底层 时间复杂度)

    比起之前那些问计数哈希表的题目,这道题好像更接近哈希表的底层机制. java中hashmap的实现是通过List<Node>,即链表的list,如果链表过长则换为红黑树,如果容量不足(装填 ...

  3. Map - leetcode [哈希表]

    149. Max Points on a Line unordered_map<float, int> hash 记录的是斜率对应的点数 unordered_map<float, i ...

  4. leetcode.哈希表.128最长连续序列-Java

    1. 具体题目 给定一个未排序的整数数组,找出最长连续序列的长度.要求算法的时间复杂度为 O(n). 示例: 输入: [100, 4, 200, 1, 3, 2] 输出: 4 解释: 最长连续序列是 ...

  5. [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针

    一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...

  6. 拼写单词[哈希表]----leetcode周赛150_1001

    题目描述: 给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars. 假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我 ...

  7. LeetCode刷题总结-哈希表篇

    本文总结在LeetCode上有关哈希表的算法题,推荐刷题总数为12题.具体考察的知识点如下图: 1.数学问题 题号:149. 直线上最多的点数,难度困难 题号:554. 砖墙,难度中等(最大最小边界问 ...

  8. 重复的DNA序列[哈希表] LeetCode.187

    所有 DNA 由一系列缩写为 A,C,G 和 T 的核苷酸组成,例如:"ACGAATTCCG".在研究 DNA 时,识别 DNA 中的重复序列有时会对研究非常有帮助. 编写一个函数 ...

  9. C#LeetCode刷题-哈希表

    哈希表篇 # 题名 刷题 通过率 难度 1 两数之和 C#LeetCode刷题之#1-两数之和(Two Sum) 42.8% 简单 3 无重复字符的最长子串   24.2% 中等 18 四数之和   ...

随机推荐

  1. 【Spring】入门HelloWorld

    参考:https://www.yiibai.com/spring/spring-tutorial-for-beginners.html 一.创建项目 1.利用IntelliJ创建Maven项目 2.配 ...

  2. Hive数据倾斜解决方案

    https://blog.csdn.net/yu0_zhang0/article/details/81776459 https://blog.csdn.net/lxpbs8851/article/de ...

  3. some knowledge of the IT world

    IT世界一切皆是可信息化(数据的转换)即信息记录一切,对信息的控制{存储,运算,传输{信息的位置转移},转换}就是对一切的控制{硬件(实质维)以信息的控制{软件形式(存在维)}进行操作} 信息本身的实 ...

  4. FPGA计算中定标与位扩展的实现

    我不知道名字取对没有,在FPGA计算中有时往往需要在不溢出的情况下将数扩大,从而获得更好的计算精度. 比如.在一个8位宽的系统中,将x=0000_0010,算术左移m=5位之后得到xt=0100_00 ...

  5. Linux 区别 chown和chmod的用法

    chown用法用来更改某个目录或文件的用户名和用户组的chown 用户名:组名 文件路径(可以是就对路径也可以是相对路径)例1:chown root:root /tmp/tmp1就是把tmp下的tmp ...

  6. 《HTTP权威指南》5-Web服务器

    各种形状,风格,尺寸的Web服务器 Web服务器会对HTTP请求进行处理并提供响应.Web服务器有着不同的风格,形状和尺寸但是不管功能,外貌,风格有何差异,所有的Web服务器都能够接收请求资源的HTT ...

  7. ubuntu 16.04 安装 ssh

    只要一条命令: sudo apt-get install openssh-server

  8. JavaScript之DOM创建节点

    上几篇文章中我们罗列了一些获取HTML页面DOM对象的方法,当我们获取到了这些对象之后,下一步将对这些对象进行更改,在适当的时候进行对象各属性的修改就形成了我们平时看到的动态效果.具体js中可以修改D ...

  9. Android 自定义 View 绘制

    在 Android 自定义View 里面,介绍了自定义的View的基本概念.同时在 Android 控件架构及View.ViewGroup的测量 里面介绍了 Android 的坐标系 View.Vie ...

  10. 还在使用SimpleDateFormat?

    阅读本文大概需要 3.2 分钟. 前言 日常开发中,我们经常需要使用时间相关类,想必大家对SimpleDateFormat并不陌生.主要是用它进行时间的格式化输出和解析,挺方便快捷的,但是Simple ...