训练营Day6
# 242.有效的字母异位词 (opens new window)
这个题目的意思是,给两个由26个小写字母组成的单词,判断两个单词的字母出现次数是否一样。
这个可以考虑使用哈希表的思维,即将字母映射到特定的数组的下标。数组的值就表示字母出现的次数。
最后统计两个单词出现的次数。
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length()!=t.length()){
return false;
}
int[] aSet = new int[26];
for (int i = 0;i<s.length();i++){
aSet[(int)s.charAt(i)-'a']++;//a单词增加
aSet[(int)t.charAt(i)-'a']--;//b单词减少
}
for (int i = 0; i < 26; i++) {
if (aSet[i]!=0){
return false;
}
}
return true;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 349.两个数组的交集 (opens new window)
思维给上面的题目类似,因为leetcode限制了数组里面的数据的大小。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> resSet = new HashSet<>();
int[] res = new int[1000];
for(int i=0;i<nums1.length;i++){
res[nums1[i]]=1;
}
for(int i=0;i<nums2.length;i++){
if(res[nums2[i]]==1){
resSet.add(nums2[i]);
}
}
return resSet.stream().mapToInt(x -> x).toArray();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 202.快乐数 (opens new window)
可以使用一个set来保存数字,如果已经出现过了,就证明他是循环的了。所以就跳出
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> record = new HashSet<>();
while(n!=1 && !record.contains(n)){
record.add(n);
n= getNextNum(n);
}
return n==1;
}
private int getNextNum(int n){
int res = 0;
while(n>0){
int temp = n%10;
res+=temp*temp;
n = n/10;
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 1.两数之和 (opens new window)
每年都做一次的题目。。。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
if(nums==null || nums.length<2){
return res;
}
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[0] = i;
res[1] = map.get(temp);
}
map.put(nums[i],i);
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上次更新: 2023/06/12, 14:30:35