2023-02-26-Daily

10-11

//1790
class Solution {
    public boolean areAlmostEqual(String s1, String s2) {
        int n=s1.length();
//        List<Integer> diff= new ArrayList<Integer>();
        ArrayList<Integer> diff = new ArrayList<Integer>();//diff 后面按alt+enter
        for (int i=0;i<n;i++){
            if(s1.charAt(i)!=s2.charAt(i)){//charAt不能超过数组大小
                diff.add(i);
                if(diff.size()>2){
                    return false;
                }
            }
        }

        if(diff.isEmpty()){
            return true;
        }

        if(diff.size()!=2){
            return false;
        }

        return s1.charAt(diff.get(0))==s2.charAt(diff.get(1)) && s1.charAt(diff.get(1))==s2.charAt(diff.get(0));


     }
}

10-12

/*
HashSet 方法
1底层使用哈希表实现
2元素不可重复
3排列无序(准确说,应该是其不保证有序。迭代器在遍历HashSet时,大多情况下是无序的,但也可能由于巧合,使其输出恰好为有序,这也是允许的。所以你的程序不应该依赖这个巧合的有序情况,而应该按照无序这种普适的情况进行处理)
4存取速度快
5线程不安全
*/
class Solution {
    public int numComponents(ListNode head, int[] nums) {
        Set<Integer> numsSet = new HashSet<Integer>();
        //集合(Set)是不允许重复值的。所以HashSet是一个没有重复元素的集合

        for (int num:nums){
            numsSet.add(num);
        }
        boolean inSet=false;
        int res=0;
        while (head!=null){
            if (numsSet.contains(head.val)){
                if(!inSet){
                    inSet=true;
                    res++;
                }
            }else {
                inSet=false;
            }
            head=head.next;
        }

        return res;


    }
}

10-13

class Solution {
    public int maxChunksToSorted(int[] arr) {
        int m = 0, res = 0;
        for (int i = 0; i < arr.length; i++) {
            m = Math.max(m, arr[i]);
            if (m == i) {
                res++;
            }
        }
        return res;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/max-chunks-to-make-sorted/solutions/1886333/zui-duo-neng-wan-cheng-pai-xu-de-kuai-by-gc4k/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2023-06-29 17:41  苏春雨1024  阅读(5)  评论(0)    收藏  举报