首页 > 其他分享 >代码随想录第六天 | 242.有效的字母异位词, 349. 两个数组的交集, 202. 快乐数, 1. 两数之和

代码随想录第六天 | 242.有效的字母异位词, 349. 两个数组的交集, 202. 快乐数, 1. 两数之和

时间:2022-10-17 15:47:24浏览次数:91  
标签:map 202 return int res 随想录 length new 两数

休息日结束后的第一天

242. 有效的字母异位词

class Solution {
    public boolean isAnagram(String s, String t) {
        HashMap<Character,Integer> map = new HashMap<>();

        if(s.length() != t.length()){
            return false;
        }  

        for(int i = 0; i< s.length(); i++){
            map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0)+1);
        }
        for(int i = 0; i< t.length(); i++){
            if(!map.containsKey(t.charAt(i))){
                return false;
            }
            if(map.get(t.charAt(i)) <= 0){
                return false;
            }
            else{
                map.put(t.charAt(i), map.get(t.charAt(i))-1);
            }
            
        }
        return true;
    }
}

把s里的每个字母都放到hashMap里,然后与s中的逐一进行对比。

349. 两个数组的交集

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int m = nums2.length;
        ArrayList<Integer> res = new ArrayList<>();

        HashSet<Integer> set = new HashSet<>();
        int k = 0;
        for(int i = 0; i<n; i++){
            
                set.add(nums1[i]);
                
            
            
        }
        for(int i =0; i<m; i++){
            if(set.contains(nums2[i])){
                set.remove(nums2[i]);
                res.add(nums2[i]);
                k++;
            }
        }
        
        int[] resArray = new int[k];
        for(int nums : res){
            resArray[--k] = nums; 
        }
        return resArray;
    }
}

一样的思路,把hashMap换成hashSet

202. 快乐数

class Solution {
    public boolean isHappy(int n) {
        HashSet<Integer> set = new HashSet<>();
        while(true){
            set.add(n);
            n = sum(n);
            if(n == 1){
                return true;
            }
            if(set.contains(n)){
                return false;
            }
        }
    }
    public int sum(int n){
        int res = 0;
        while(n > 0){
            int temp = n %10;
            res += temp * temp;
            n = n/10;
        }
        return res;
    }
}

看有没有重复的和出现,没有的话直到数字为1为止。

1. Two Sum

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        int[] res = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i< n; i++){
            if(map.containsKey(target-nums[i])){
                res[0] = map.get(target - nums[i]);
                res[1] = i;
            }
            map.put(nums[i], i);
        }
        return res;
    }
}

不多说了,梦开始的地方

 

今天的四道题都是简单,按照上周的情况,明天开始就会需要综合多个知识点了。

 

标签:map,202,return,int,res,随想录,length,new,两数
From: https://www.cnblogs.com/catSoda/p/16799393.html

相关文章