当前位置:网站首页>Search, insert and delete of hash table
Search, insert and delete of hash table
2022-07-27 21:32:00 【Al_ tair】
Search, insert and delete hash table
Hello, everyone , I'm Xiao Sheng , This week I'll share some hash table algorithm exercises
Search, insert and delete hash table
217. There are duplicate elements
217. There are duplicate elements
Given an array of integers , Determine whether there are duplicate elements
If a value exists, it appears at least twice in the array , The function returns
true. If every element in the array is different , Then return tofalseExample 1:
Input : [1,2,3,1] Output : trueExample 2:
Input : [1,2,3,4] Output : falseExample 3:
Input : [1,1,1,3,3,4,3,2,4,2] Output : true
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i=0;i<nums.length-1;i++){
if(nums[i]==nums[i+1]){
return true;
}
}
return false;
}
}
349. Intersection of two arrays
349. Intersection of two arrays
Given two arrays , Write a function to calculate their intersection .
Example 1:
Input :nums1 = [1,2,2,1], nums2 = [2,2] Output :[2]Example 2:
Input :nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output :[9,4]explain :
- Each element of the output must be unique .
- We can ignore the order of output results .
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1.length*nums2.length == 0) return null;
HashSet<Integer> sites = new HashSet<>();
int index = 0;
int[] array = new int[nums1.length<nums2.length?nums1.length:nums2.length];
for(int i=0;i<nums1.length;i++){
for(int j=0;j<nums2.length;j++){
if(nums1[i]==nums2[j] && sites.add(nums1[i])){
array[index] = nums1[i];
index++;
}
}
}
int[] array2 = new int[index];
for(int i=0;i<index;i++){
array2[i] = array[i];
}
return array2;
}
}
202. Happy number
The difficulty is simple 730
Write an algorithm to judge a number
nIs it a happy number .「 Happy number 」 Defined as :
- For a positive integer , Replace the number with the sum of the squares of the numbers in each of its positions .
- Then repeat the process until the number becomes 1, It could be Infinite loop But it doesn't change 1.
- If It can be 1, So this number is the happy number .
If
nIf it's happy, count it backtrue; No , Then return tofalse.Example 1:
Input :n = 19 Output :true explain : 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1Example 2:
Input :n = 2 Output :falseTips :
1 <= n <= 231 - 1
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();
while(n != 1){
n = happyTurn(n);
if(n == 1) return true;
if(!set.add(n)) return false;
}
return true;
}
public int happyTurn(int n){
int round,sum=0; // Remainder Sum up
while(n > 0){
round = n%10;
n = n/10;
sum += round*round;
}
return sum;
}
}
290. Rules of words
The difficulty is simple 403
Give a rule
patternAnd a stringstr, JudgestrFollow the same rule .there follow Finger perfect match , for example ,
patternEach letter and string instrThere is a two-way connection between each non empty word in .Example 1:
Input : pattern = "abba", str = "dog cat cat dog" Output : trueExample 2:
Input :pattern = "abba", str = "dog cat cat fish" Output : falseExample 3:
Input : pattern = "aaaa", str = "dog cat cat dog" Output : falseExample 4:
Input : pattern = "abba", str = "dog dog dog dog" Output : falseexplain :
You can assumepatternContains only lowercase letters ,strContains lowercase letters separated by a single space .
class Solution {
public boolean wordPattern(String pattern, String s) {
HashMap<String,Character> StrChar = new HashMap<>();
HashMap<Character,String> CharStr = new HashMap<>();
int n = s.length(),m=pattern.length(),sIndex=0,patternIndex=0;
while(--m >=0){
char ch = pattern.charAt(patternIndex++);
String str = "";
if(sIndex>=n) break;
for(int i=sIndex;i<n && s.charAt(i)!=' ';i++){
str += s.charAt(i)+"";
sIndex++;
}
sIndex+=1;
if(StrChar.containsKey(str)&&StrChar.get(str)!=ch){
return false;
}
if(CharStr.containsKey(ch)&&!CharStr.get(ch).equals(str)){
return false;
}
StrChar.put(str,ch);
CharStr.put(ch,str);
}
return m<0&&sIndex>=n;
}
}
205. Isomorphic Strings
The difficulty is simple 405
Given two strings s and *t*, Judge whether they are isomorphic .
If s The characters in can be replaced according to some mapping relationship *t* , So these two strings are isomorphic .
Every character that appears should be mapped to another character , Without changing the order of characters . Different characters cannot be mapped to the same character , The same character can only be mapped to the same character , Characters can be mapped to themselves .
Example 1:
Input :s = "egg", t = "add" Output :trueExample 2:
Input :s = "foo", t = "bar" Output :falseExample 3:
Input :s = "paper", t = "title" Output :trueTips :
- It can be assumed s and *t* Same length .
class Solution {
public boolean isIsomorphic(String s, String t) {
HashMap<Character,Character> chst = new HashMap<>();
HashMap<Character,Character> chts = new HashMap<>();
int m=s.length(),n=t.length(),nIndex=0,mIndex=0;
char chs,cht;
if(m!=n) return false;
for(int i=0;i<m;i++){
chs = s.charAt(i);
cht = t.charAt(i);
if(chst.containsKey(chs)&&chst.get(chs)!=cht){
return false;
}
if(chts.containsKey(cht)&&chts.get(cht)!=chs){
return false;
}
chst.put(chs,cht);
chts.put(cht,chs);
}
return true;
}
}
633. Sum of squares ( Non hash table )
Given a nonnegative integer
c, You have to decide if there are two integersaandb, bringa2 + b2 = c.Example 1:
Input :c = 5 Output :true explain :1 * 1 + 2 * 2 = 5Example 2:
Input :c = 3 Output :falseExample 3:
Input :c = 4 Output :trueExample 4:
Input :c = 2 Output :trueExample 5:
Input :c = 1 Output :trueTips :
0 <= c <= 231 - 1
Method 1 : Use sqrt function
Their thinking :
- Find the maximum square by square n
- Put the maximum square n As a conditional decreasing cycle
- Until you find another subtracted square, it returns true
- If the number is not found until the end of the cycle, it returns false
class Solution {
public boolean judgeSquareSum(int c) {
int n = (int)Math.sqrt(c)+1; // +1 Just to offset n--
while(n-- > 0)
if(Math.sqrt(c-n*n) == (int)Math.sqrt(c-n*n))
return true;
return false;
}
}

Method 2 : Double pointer
- If a^2 + b^2 =c, We found a solution to the problem , return true
- If a^2 + b^2 <c, At this time, we need to a The value of the add 1, Continue to find
- If a^2 + b^2 >c, At this time, we need to b The value of the reduction 1, Continue to find
Have you ever thought about the possibility of missing
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | 0 | 1 | 4 | 9 | 16 |
| 1 | 1 | 2 | 5 | 10 | 17 |
| 2 | 4 | 5 | 8 | 13 | 20 |
| 3 | 9 | 10 | 13 | 18 | 25 |
| 4 | 16 | 17 | 20 | 25 | 32 |

class Solution {
public boolean judgeSquareSum(int c) {
long left = 0;
long right = (long) Math.sqrt(c);
while (left <= right) {
long sum = left * left + right * right;
if (sum == c) {
return true;
} else if (sum > c) {
right--;
} else {
left++;
}
}
return false;
}
}
边栏推荐
- Explain cache consistency and memory barrier
- Qmodbus library is used, and it is written as ROS node publishing topic and program cmakelist
- Daily news on July 15, 2022: meta announced the launch of make-a-scene: AI image generation can be controlled based on text and sketches
- Acwing3715. Minimum exchange times (simulation idea of bubble sorting method)
- How to check whether there is Tsinghua source / delete Tsinghua source and keep the default source
- @Autowired注解与@Resource注解的区别
- 软件测试面试题:通过画因果图来写测试用例的步骤为___、___、___、___及把因果图转换为状态图共五个步骤。 利用因果图生成测试用例的基本步骤是?
- The application of building cloud rendering is expanding, and more and more industries are in urgent need of visualization services
- What is the value of digital factory management system
- Common ArrayList interview questions
猜你喜欢

30分钟彻底弄懂 synchronized 锁升级过程
![[2022 Niuke multi School Game 2] k-link with bracket sequence I](/img/95/9d6710bfb7b9282b4a06a5f61a1f08.png)
[2022 Niuke multi School Game 2] k-link with bracket sequence I

puzzle(021)消除问题

Guava Cache 原理分析与最佳实践

ACM mm 2022 | Zhejiang University proposed: point cloud segmentation, active learning of new SOTA

一文读懂Plato Farm的ePLATO,以及其高溢价缘由

MySQL back to table, SQL optimization, four isolation levels, three logs binlog, redo log, undo log

The new CTO strongly prohibits the use of calendar?

What are the product performances of industrial Ethernet switches?

Can single mode and multi-mode of industrial switches replace each other?
随机推荐
Implicit intent
新来个技术总监要我做一个 IP 属地功能~
Simple use of express web server
简单手动实现Map
What are the product performances of industrial Ethernet switches?
监听服务器jar运行,及重启脚本
中英文说明书丨人甲胎蛋白(AFP)ELISA定量试剂盒
Graphic SQL, this is too vivid!
软件测试面试题:软件验收测试包括正式验收测试、alpha测试、beta测试三种测试?
Unity installs personal free edition
Worthington plasma amine oxidase (PAO) instructions
中国能否在元宇宙的未来发展中取得突破,占领高地?
对L1正则化和L2正则化的理解[通俗易懂]
Force buckle 919. Complete binary tree inserter
Daily Mathematics Series 60: February 29
Report design - how to make your powerbi Kanban brilliant?
软件测试面试题:什么是回归测试?
Daily news on July 15, 2022: meta announced the launch of make-a-scene: AI image generation can be controlled based on text and sketches
How to speed up the memory database through special data type index
What are the practical advantages of digital factory system