有效的字母异位词-day05

题目:有效的字母异位词
代码链接:https://leetcode.cn/problems/valid-anagram/solutions/6690/hua-jie-suan-fa-242-you-xiao-de-zi-mu-yi-wei-ci-by/
思路: 两个字符串由完全相同的英文字母组成,每个字母出现的次数也完全相同,只是字母的排列顺序不同
代码:
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()){
return false;
}
int[] count=new int[26]; //统计26个字母出现的次数
for(int i=0;i<s.length();i++){
count[s.charAt(i)-'a']++; //统计s中字母的个数
count[t.charAt(i)-'a']--;
}
for(int i=0;i<26;i++){
if(count[i]!=0)// 只要
return false;
}
return true;
}

题目: 349. 两个数组的交集
题目链接:https://leetcode.cn/problems/intersection-of-two-arrays/description/
思路:判断两个数组中是否有相同的元素,第一个数组先将数据添加到去重的hashset集合中,第2个数组根据hashset中的contain方法,
将两个数组的交集添加到新的hashset集合中,在将集合转成数组
代码: public int[] intersection(int[] nums1, int[] nums2) {
if(nums1null || nums1.length0 || nums2null || nums2.length0){
return new int[0];
}
Set set1=new HashSet<>();
Set set2=new HashSet<>();
for(int i:nums1){
set1.add(i);//将nums1中的元素去重后添加到set1中
}
for(int i:nums2){
if(set1.contains(i))
set2.add(i);//set2中的元素就是两个数组的交集
}

    return set2.stream().mapToInt(Integer::intValue).toArray();
}

题目: 1. 两数之和
题目链接:https://leetcode.cn/problems/intersection-of-two-arrays/
思路:从数组中找到两个值的和是target,返回两个值对应的下标值
代码:
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])) {//找到进入if中
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);//没找到将元素添加到hashtable中
}
return new int[0];
}

posted @ 2026-01-19 20:47  whq001  阅读(1)  评论(0)    收藏  举报