有效的字母异位词
题目:LeetCode242
链接:https://leetcode.cn/problems/valid-anagram/submissions/
初看题目的时候就是想着用哈希表,但是之前没做过此类的题目,对哈希表的操作并不熟悉,所以在写代码的时候思路很乱,看了视频讲解之后了解了很多,这种情况可以用的有三种类,数组、Set(集合)还有Map(表),一般数据量比较小且清晰的时候,就可以使用数组,数据量比较大的时候就可以用Set,Map则是键值对对应的。
这道题的情况数据量比较小,只需要用数组就可以解决,在看了题解之后,自己按照思路写的代码如下:
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for(int i = 0;i<s.length();i++){
record[s.charAt(i)-'a']++;
}
for(int i = 0;i<t.length();i++){
record[t.charAt(i)-'a']--;
}
for(int count:record){
if(count!=0){
return false;
}
}
return true;
}
}
因为自己对hash表的内容不熟悉,在看题解的时候看到一个用hash表做的方法,觉得很不错可以当练手,也列出来
class Solution {
public boolean isAnagram(String s, String t) {
Map<Character,Integer> map = new HashMap<>();
for(char ch:s.toCharArray()){
map.put(ch,map.getOrDefault(ch,0)+1);
}
for(char ch:t.toCharArray()){
Integer count = map.get(ch);
if(count==null){
return false;
}else if(count>1){
map.put(ch,count-1);
}else {
map.remove(ch);
}
}
return map.isEmpty();
}
}
两个数组的交集
题目:LeetCode349
链接:https://leetcode.cn/problems/intersection-of-two-arrays/
看到这道题第一个想法就是可以用集合来确定元素不重复,接着遍历两次来输出,代码如下
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> fan1 = new HashSet<Integer>();
Set<Integer> fan2 = new HashSet<Integer>();
int x = 0,y = 0;
int min = nums1.length<nums2.length?nums1.length:nums2.length;
int[] fanhui = new int[min];
for(int i = 0;i<nums1.length;i++){
fan1.add(nums1[i]);
}
for(int i = 0;i<nums2.length;i++){
fan2.add(nums2[i]);
}
Iterator<Integer> it = fan2.iterator();
while(it.hasNext()){
Integer i = it.next();
if(fan1.contains(i)){
fanhui[x] = i;
x++;
}
}
int[] zhenfan = new int[x];
for(int i =0;i<x;i++){
zhenfan[i]=fanhui[i];
}
return zhenfan;
}
}
快乐数
题目:LeetCode202
链接:https://leetcode.cn/problems/happy-number/
看到题目的第一眼没有什么思路,想了挺久没有搞清楚,看了题解才搞懂,这道题也给我们提供了一个思路 ,看了题解之后代码如下:
class Solution {
public boolean isHappy(int n) {
if(n<=0)return false;
Set<Integer> se = new HashSet<>();
if(n==1){
return true;
}
while(!se.contains(n)){
se.add(n);
n = getNext(n);
}
return n==1;
}
public int getNext(int num){
int sum = 0;
if(num<10){
return num*num;
}
while(num>=10){
int b = num%10;
sum = sum + (b*b);
num = num/10;
if(num<10){
sum = sum +(num*num);
}
}
return sum;
}
}
两数之和
题目:LeetCode1
链接:https://leetcode.cn/problems/two-sum/
第一次看到这道题,想到的是暴力解决的办法,但是想不到哈希表的解决办法,还是看了讲解之后才懂,还是对哈希表的了解不够深入,需要加强,代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}