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. search

    |—search()—|—添加一个列表变量Expend,存储每个小格扩展时为第几步,可打印出 |                    |—打印运动表 |—A*—|— heuristic() |—Dy ...

  2. Oracle 12c client with .NET legacy Oracle driver

    如果使用Oracle 12c Client和.NET的Oracle driver,你很可能会碰到跟下面一样的问题: https://www.codeproject.com/Questions/8767 ...

  3. day_10初级函数

    今天讲了函数初级 函数:完成特定功能的代码块,作为一个整体对其进行特定的命名,该名字就是代表函数 --现实中很多问题要通过一些工具进行处理 ,,可以将工具提前准备好并命名 通过名字就可以找到这个工具 ...

  4. react-native 项目初始化

    react-native 项目初始化 搭建java,android,node环境 http://www.cnblogs.com/morang/p/react-native-java-build.htm ...

  5. bash 管理小脚本

    #!/bin/bash shell_user="root" shell_pass="1233" shell_port="22" shell_ ...

  6. 微信团队分享:Kotlin渐被认可,Android版微信的技术尝鲜之旅

    本文由微信开发团队工程是由“oneliang”原创发表于WeMobileDev公众号,内容稍有改动. 1.引言   Kotlin 是一个用于现代多平台应用的静态编程语言,由 JetBrains 开发( ...

  7. Javascript高级编程学习笔记(34)—— 客户端检测(3)用户代理检测

    用户代理检测 前面的文章介绍的是如何检测浏览器对某一功能的支持情况 但是在实践中我们有些时候免不了需要知道用户到底是用的什么浏览器对我们的站点进行访问 这也是统计用户行为的一部分 用户代理检测这种方式 ...

  8. Conflict with dependency 'com.android.support:support-annotations' in project ':xxx'. Resolved versions for app (25.4.0) and test app (27.1.1) differ 问题解决

    Conflict with dependency 'com.android.support:support-annotations' in project ':xxx'. Resolved versi ...

  9. 微信小程序的概要

    微信小程序的概要 学习小程序要了解一下什么事小程序,小程序开发前需要做哪些准备,微信小程序开发工具的使用,小程序中的目录结构解析,视图和渲染,事件. 小程序的配置详解,小程序的生命周期与app对象的使 ...

  10. idea 过段时间java程序包不存在问题 ?

    有时候我们在导入程序之后,系统会给出错误提示:Java:程序包xxxx不存在,现在我这里有一招,就是使用IDEA自动导入Java程序包,这也是IDEA的一大优点. 但是在看到这个问题的文章的时候,并不 ...