代码随想录算法训练营第五天|LeetCode 242.有效的字母异位词、LeetCode 349. 两个数组的交集、LeetCode 202. 快乐数、LeetCode 1. 两数之和

1.LeetCode 242.有效的字母异位词

题目链接:https://leetcode.cn/problems/valid-anagram/description/
文章链接:https://programmercarl.com/0242.%E6%9C%89%E6%95%88%E7%9A%84%E5%AD%97%E6%AF%8D%E5%BC%82%E4%BD%8D%E8%AF%8D.html
视频链接:https://www.bilibili.com/video/BV1YG411p7BA

在这里插入图片描述

思路:
解题关键是:
①确定什么是字母异位词。即,s与t中有相同的字符,且s与t中出现的字符的次数相同,并不是t包含s。
②定义一个长度为26的数组,遍历s中的字符,在s[i] - ‘a’ 索引处+1;遍历t中的字符,在t[i] - 'a’索引处-1。判断最终数组是否全为0,若是,则为字母异位词;否则,返回false。

解法:
class Solution {
    // public boolean isAnagram(String s, String t) {
    //     Map<Character,Integer> t_map=new HashMap<>();
    //     for(int i=0;i<t.length();i++){
    //         if(t_map.get(t.charAt(i))==null){
    //             t_map.put(t.charAt(i),1);
    //         }else{
    //             t_map.put(t.charAt(i),t_map.get(t.charAt(i))+1);
    //         }
    //     }

    //     for(int j=0;j<s.length();j++){
    //         if(t_map.get(s.charAt(j))==null){
    //             return false;
    //         }else{
    //             t_map.put(s.charAt(j),t_map.get(s.charAt(j))-1);
    //         }
    //     }

    //     for(Integer i:t_map.values()){
    //         if(i!=0){
    //             return false;
    //         }
    //     }
    //     return true;

    // }

    public boolean isAnagram(String s, String t) {
        int[] res=new int[26];
        for(int i=0;i<s.length();i++){
            res[s.charAt(i)-'a']++;
        }

        for(int j=0;j<t.length();j++){
            res[t.charAt(j)-'a']--;
        }

        for(int count:res){
            if(count!=0){
                return false;
            }
        }
        return true;
    }
}

2.LeetCode 349. 两个数组的交集

题目链接:https://leetcode.cn/problems/intersection-of-two-arrays/description/
文章链接:https://programmercarl.com/0349.%E4%B8%A4%E4%B8%AA%E6%95%B0%E7%BB%84%E7%9A%84%E4%BA%A4%E9%9B%86.html
视频链接:https://www.bilibili.com/video/BV1ba411S7wu

在这里插入图片描述

思路:
解题的关键是:
①保证输出结果的元素唯一性,因此用到Set集合存储元素。
②集合转数组的方式。

解法:
class Solution {
    // public int[] intersection(int[] nums1, int[] nums2) {
    //     List<Integer> list = new ArrayList<>();
    //     Map<Integer,Integer> map1 = new HashMap<>();
        
    //     for(int i=0;i<nums1.length;i++){
    //         map1.put(nums1[i],1);
    //     }

    //     for(int j=0;j<nums2.length;j++){
    //         if((map1.get(nums2[j])!=null)&&!list.contains(nums2[j])){
    //             list.add(nums2[j]);
    //         }
    //     }

    //      // 将list转换为int数组
    //     int[] result = new int[list.size()];
    //     for (int i = 0; i < list.size(); i++) {
    //         result[i] = list.get(i);
    //     }

    //     return result;
    // }
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> resSet = new HashSet<>();
        //遍历数组1
        for (int i : nums1) {
            set1.add(i);
        }
        //遍历数组2的过程中判断哈希表中是否存在该元素
        for (int i : nums2) {
            if (set1.contains(i)) {
                resSet.add(i);
            }
        }
      
        // //方法1:将结果集合转为数组

        // return resSet.stream().mapToInt(x -> x).toArray();
        
        //方法2:另外申请一个数组存放setRes中的元素,最后返回数组
        int[] arr = new int[resSet.size()];
        int j = 0;
        for(int i : resSet){
            arr[j++] = i;
        }
        
        return arr;
    }
}

代码解析:
将结果集合resSet转为数组的两种方式:
①resSet.stream().mapToInt(x -> x).toArray();

int[] arr = new int[resSet.size()];
int j = 0;
for(int i : resSet){
      arr[j++] = i;
}

3.LeetCode 202. 快乐数

题目链接:https://leetcode.cn/problems/happy-number/description/
文章链接:https://programmercarl.com/0202.%E5%BF%AB%E4%B9%90%E6%95%B0.html

在这里插入图片描述

思路:
循环的出现是因为出现了访问过的数值,因此需要一个集合存储访问过的值,每次遍历时检查传入的值是否已经被访问了:
若被访问过,则判断是否等于1,并返回判断值;
若未被访问过,则添加到集合中,并拆分平方更新值。

解法:
class Solution {
    // public boolean isHappy(int n) {
    //     Set<Integer> set=new HashSet<>();
    //     while(n!=1&&!set.contains(n)){
    //         set.add(n);
    //         n=find(n);
    //     }

    //     return n==1;
    // }

    public boolean isHappy(int n) {
        Set<Integer> set=new HashSet<>();
        while(!set.contains(n)){
            set.add(n);
            n=find(n);//求不同位置上的数值平方和
        }

        return n==1;
    }

    // public int find(int m){
    //     int count=String.valueOf(m).length();
    //     int res=0;

    //     while(count>0){
    //         int i=(int) Math.pow(10, count-1);
    //         res+=(int) Math.pow(m/i, 2);
    //         m = m - i*(m/i);
    //         count--;
    //     }
    //     return res;
    // }

    public int find(int n){
        int res=0;
        while(n>0){
            int temp = n%10;
            res+=temp*temp;
            n=n/10;
        }  
        return res;
    }
}

代码分析:
关键代码:如何计算一个值不同位置上值的平方和,如下所示:

public int find(int n){
      int res=0;
      while(n>0){
          int temp = n%10;
          res+=temp*temp;
          n=n/10;
      }  
      return res;
}

4.LeetCode 1. 两数之和

题目链接:https://leetcode.cn/problems/two-sum/submissions/539056146/
文章链接:https://programmercarl.com/0001.%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
视频链接:https://www.bilibili.com/video/BV1aT41177mK

在这里插入图片描述

思路:
1.由于最终返回的是下标,但是判断的是数组值,因此,可以使用map集合,其中key为数组值,value为下标。这样只需比较数组值,得到结果后,根据数组值从Map集合中获取下标。
2.集合存储的是已被访问的值,对于新值nums[i],我们只需要判断集合中是否存在一个值可以与新值相加等于target。若不存在,则将新值和其下标加入map中;若存在,则返回结果。判断逻辑如下:

int temp=target-nums[i];
if(map.containsKey(temp)){
......
}
解法:
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        int[] res = new int[2];
        if(nums==null||nums.length==0){
            return res;
        }
        
        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);
                return res;
            }else{
                map.put(nums[i],i);
            }
        }

        return res;
    }
}
  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
第二十二天的算法训练营主要涵盖了Leetcode题目中的三道题目,分别是Leetcode 28 "Find the Index of the First Occurrence in a String",Leetcode 977 "有序数组的平方",和Leetcode 209 "长度最小的子数组"。 首先是Leetcode 28题,题目要求在给定的字符串中找到第一个出现的字符的索引。思路是使用双指针来遍历字符串,一个指向字符串的开头,另一个指向字符串的结尾。通过比较两个指针所指向的字符是否相等来判断是否找到了第一个出现的字符。具体实现的代码如下: ```python def findIndex(self, s: str) -> int: left = 0 right = len(s) - 1 while left <= right: if s[left == s[right]: return left left += 1 right -= 1 return -1 ``` 接下来是Leetcode 977题,题目要求对给定的有序数组中的元素进行平方,并按照非递减的顺序返回结果。这里由于数组已经是有序的,所以可以使用双指针的方法来解决问题。一个指针指向数组的开头,另一个指针指向数组的末尾。通过比较两个指针所指向的元素的绝对值的大小来确定哪个元素的平方应该放在结果数组的末尾。具体实现的代码如下: ```python def sortedSquares(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 ans = [] while left <= right: if abs(nums[left]) >= abs(nums[right]): ans.append(nums[left ** 2) left += 1 else: ans.append(nums[right ** 2) right -= 1 return ans[::-1] ``` 最后是Leetcode 209题,题目要求在给定的数组中找到长度最小的子数组

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值