今日的任务:
- 哈希表理论基础
- 242.有效的字母异位词
- 202.快乐数
- 1.两数之和
哈希表理论基础
主要有三种数据结构,Set, Array and Map.
Hash Table: maps Key to values.
一般哈希表都是用来快速判断一个元素是否出现在集合里。
Strength:时间复杂度只有O(1).(相比于枚举的话,枚举的时间复杂度要达到O(n)).
Weakness:Hashtable是利用空间来换取了时间的典型,因为采用了额外的数组,集合和映射来存放数据。
总结得差不多了,现在开始今天的训练题吧!
第一题
我们可以通过题意得知,首先该题不需要去重,所以可以很快的想到使用Hash Table将First String每个字母都放入一个存有26个字母的Array中,然后再代入Second String,遇到重复的字母就将该字母对应的Value减1.如果最后Array中对应的value值都是0,则返回True. Otherwise, return false.
class Solution {
public boolean isAnagram(String s, String t) {
int[] alphabet = new int[26];
for(int i=0; i<s.length(); i++){
alphabet[s.charAt(i)-'a']++; //ASC码,对比与a起始的长度,对应Array中的值
}
for(int j=0; j<t.length(); j++){
alphabet[t.charAt(j)-'a']--;
}
for(int n: alphabet){ //遍历Array,验证是否消除
if(n != 0){
return false;
}
}
return true;
}
}
第二题
until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
上面这句话,其实是非常重要的一句话,结束循环的条件是 n==1 or 陷入无限循环,So 只要一个数重复出现一次,就可以结束循环。因此,设计while的判断条件时应该由两部分组成,且保持&&(与)的关系。
每个数重复出现就跳出循环,完全符合Hash Table判断条件。
Attention: happyNumber.contains(n);这个语法
In addition, 该题我用了LIst<Integer> happyNumber = new ArrayList<>();并没有采用老师的HashSet,例如:
Set<Integer> happyNumber = new HashSet<>();
class Solution {
public boolean isHappy(int n) {
List<Integer> happyNumber = new ArrayList<Integer>();
while(n != 1 && !happyNumber.contains(n)){ //如果只有n != 1 so Loop endlessly
happyNumber.add(n);
n = getNextNumber(n);
}
return n == 1; //判断n 是否== 1
}
public int getNextNumber(int n){
int res = 0;
while(n > 0){ //每次都取末尾的个位数平方,直到最后一位
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
}
第三题
分析一下题意,其实这道题并没有要求数字连续,只要其中任意两数之和加起来等于Target就可以。注意注意!!!两数之和在这里是非常重要的一个条件,后续题目还有三数,四数之和!(到时候再总结)
And what the question say is Each Input would have exactly one solution, and you cannot use the same element twice.
其次,最后输出的index,所以采用HashMap比较合适,还需要一个Array,返回输入的两个index
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
}
map.put(nums[i],i);
}
return res;
}
}