Java算法(六):1.力扣:有效字母的异位词、两个数组的交集、快乐数、四数相加Ⅱ、二叉树的中序、层序遍历 2.判断一个链表是否回文

哈希表:

1.有效字母的异位词

/*
        给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
        注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。
     */
    public static void main(String[] args) {
        isAnagram("anagram", "nagaram");
        isAnagram("rat", "car");
    }

    //哈希表
    public static boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        HashMap<Character, Integer> hashMap = new HashMap<>();
        char[] sChars = s.toCharArray();
        char[] tChars = t.toCharArray();

        for (char sChar : sChars) {
            hashMap.put(sChar, hashMap.getOrDefault(sChar, 0) + 1); //根据key取值,没有key则value默认为0
            //System.out.println(hashMap);
        }
        for (char tchar : tChars) {
            hashMap.put(tchar, hashMap.getOrDefault(tchar, 0) - 1);
            //ystem.out.println(hashMap);
            if (hashMap.get(tchar) < 0) { //tChar < 0, 则说明两字符串中某字符出现的次数不一样
                System.out.println(false);
                return false;
            }
        }
        System.out.println(true);
        return true;
    }

2.两个数组的交集

/*
        给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。
        我们可以 不考虑输出结果的顺序 。
     */
    public static void main(String[] args) {
        intersection(new int[]{1, 2, 2, 1}, new int[]{2, 2});
        intersection(new int[]{4, 9, 5}, new int[]{9, 4, 9, 8, 4});
    }

    //首先使用两个集合分别存储两个数组中的元素,然后遍历较小的集合,判断其中的每个元素是否在另一个集合中,
    // 如果元素也在另一个集合中,则将该元素添加到返回值。
    public static int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for (int num : nums1) {
            set1.add(num);
        }
        for (int num : nums2) {
            set2.add(num);
        }
        return getIntersection(set1, set2);
    }

    public static int[] getIntersection(Set<Integer> set1, Set<Integer> set2) { //求两集合的交集
        if (set1.size() > set2.size()) { //默认set1较大,若set2较大则反转
            return getIntersection(set2, set1);
        }
        Set<Integer> hashSet = new HashSet<>();
        for (int num : set1) { //遍历较小的集合
            if (set2.contains(num)) { //判断其中的每个元素是否在另一个集合中
                hashSet.add(num);
            }
        }

        int[] arr = new int[hashSet.size()]; //初始化一个长度为交集个数的数组
        int index = 0;
        for (int num : hashSet) { //遍历hashSet
            arr[index++] = num;
            System.out.println(num);
        }
        System.out.println("------------------");
        return arr;
    }

3.快乐数

/*
        编写一个算法来判断一个数 n 是不是快乐数。

        「快乐数」 定义为:
        * 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
        * 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
        * 如果这个过程 结果为 1,那么这个数就是快乐数。
        如果 n 是 快乐数 就返回 true ;不是,则返回 false 。
     */
    public static void main(String[] args) {
        isHappy(19);
        isHappy(2);
    }

    //哈希表
    public static boolean isHappy(int n) {
        Set<Integer> hashSet = new HashSet<>();
        while (n != 1 && !hashSet.contains(n)) { //把n 每一次 不等于1的变换存到哈希表中
            hashSet.add(n);
            n = getNext(n);
        }
        System.out.println("-----------------");
        return n == 1;
    }
    public static int getNext(int n) {
        int sum = 0;
        while (n > 0) {
            int d = n % 10; //个位
            n = n /10;  //十位,百位...
            sum += d * d;
        }
        System.out.println(sum);
        return sum;
    }

4.四数相加Ⅱ

/*
        给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:
        * 0 <= i, j, k, l < n
        * nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
     */
    public static void main(String[] args) {
        fourSumCount(new int[]{1, 2}, new int[]{-2, -1}, new int[]{-1, 2}, new int[]{0, 2});
        fourSumCount(new int[]{0}, new int[]{0}, new int[]{0}, new int[]{0});
    }

    //分组 + 哈希表
    public static int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        Map<Integer, Integer> hashMap = new HashMap<>();
        //键:任意两数组不同元素的所有和,   值:和出现的次数
        for (int i : nums1) {
            for (int j : nums2) {
                hashMap.put(i + j, hashMap.getOrDefault(i + j, 0) + 1);
            }
        }
        //判断两个组(nums1和nums2组,nums3和nums4组) 是否能相加为0
        int ans = 0;
        for (int i : nums3) {
            for (int j : nums4) {
                if(hashMap.containsKey(-i - j)) {
                    ans += hashMap.get(-i - j);
                }
            }
        }
        System.out.println(ans);
        return ans;
    }

二叉树:

1. 用递归与非递归的方式实现二叉树的先序,中序,后序遍历
2. 实现层次遍历

TreeNode类:

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode() {
    }

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

}

5.二叉树的中序遍历

/*
        给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
     */

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        inorder(root, res);
        return res;
    }

    public void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }

6.二叉树的层序遍历

/*
        给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
     */

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<Integer>();
            int currentLevelSize = queue.size();
            for (int i = 1; i <= currentLevelSize; ++i) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            ret.add(level);
        }
        return ret;
    }

链表:

ListNode类:

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

7.判断一个链表是否回文

(1)栈:

public boolean isPalindrome(ListNode head) {
        if (head == null)
            return true;
        ListNode temp = head;
        Stack<Integer> stack = new Stack();

        int len = 0; //链表的长度
        while (temp != null) {  //把链表节点的值存放到栈中
            stack.push(temp.val);
            temp = temp.next;
            len++;
        }

        len >>= 1; //len长度除以2
        while (len-- >= 0) { //然后再出栈
            if (head.val != stack.pop())
                return false;
            head = head.next;
        }
        return true;
    }

(2)反转链表:

public boolean isPalindrome2(ListNode head) {
        ListNode fast = head, slow = head;

        while (fast != null && fast.next != null) { //通过快慢指针找到中点
            fast = fast.next.next;
            slow = slow.next;
        }
        if (fast != null) { //如果fast不为空,说明链表的长度是奇数个
            slow = slow.next;
        }

        slow = reverse(slow);  //反转后半部分链表
        fast = head;

        while (slow != null) {
            if (fast.val != slow.val)  //然后比较,判断节点值是否相等
                return false;
            fast = fast.next;
            slow = slow.next;
        }
        return true;
    }

    public ListNode reverse(ListNode head) { //反转链表
        ListNode prev = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
力扣第二题是一道链表相关的题目,要求实现一个来将两个非负整链表相加,并返回一个新的链表表示它们的和。 在解决这个问题时,可以设立一个表示进位的变量carried,并建立一个新的链表来存储结果。然后,使用while循环来同时处理两个输入链表,每次取出对应的节点值相加,并将结果加上进位值carried后的值作为一个新节点加入新链表的后面。当遍历完两个链表后,如果最后还有进位,需要再添加一个节点来存储进位的值。最后返回新链表的头节点即可。 下面是使用Java语言编写的实现代码: ```java public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); int sum = 0; ListNode cur = dummy; ListNode p1 = l1, p2 = l2; while (p1 != null || p2 != null) { if (p1 != null) { sum += p1.val; p1 = p1.next; } if (p2 != null) { sum += p2.val; p2 = p2.next; } cur.next = new ListNode(sum % 10); sum /= 10; cur = cur.next; } if (sum == 1) { cur.next = new ListNode(1); } return dummy.next; } } ``` 以上就是力扣相加第二题的Java实现代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【Java版】LeetCode 力扣第 2 题:两相加 (Add Two Numbers)](https://blog.csdn.net/monokai/article/details/108132843)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值