【LeetCode】Day5

412. Fizz Buzz

3的倍数 输出Fizz,5的倍数输出Buzz,击时3的倍数也是5的倍数,输出FizzBuzz,否则输出数字
Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

n = 15,
Return:
[
“1”,
“2”,
“Fizz”,
“4”,
“Buzz”,
“Fizz”,
“7”,
“8”,
“Fizz”,
“Buzz”,
“11”,
“Fizz”,
“13”,
“14”,
“FizzBuzz”
]

    public List<String> fizzBuzz(int n) {
        List<String> list = new ArrayList<>(n);
        for (int i = 1; i <= n; i++) {
            if (i % 3 == 0) {
                list.add("Fizz" + (i % 5 == 0 ? "Buzz" : ""));
            } else if (i % 5 == 0) {
                list.add("Buzz");
            } else list.add(i + "");
        }
        return list;
    }

953. Verifying an Alien Dictionary

In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.

Input: words = [“hello”,“leetcode”], order = “hlabcdefgijkmnopqrstuvwxyz”
Output: true
Explanation: As ‘h’ comes before ‘l’ in this language, then the sequence is sorted.

Input: words = [“word”,“world”,“row”], order = “worldabcefghijkmnpqstuvxyz”
Output: false
Explanation: As ‘d’ comes after ‘l’ in this language, then words[0] > words[1], hence the sequence is unsorted.

Input: words = [“apple”,“app”], order = “abcdefghijklmnopqrstuvwxyz”
Output: false
Explanation: The first three characters “app” match, and the second string is shorter (in size.) According to lexicographical rules “apple” > “app”, because ‘l’ > ‘∅’, where ‘∅’ is defined as the blank character which is less than any other character (More info).

思路
普通的比较相邻两个字符串的大小,只是把比较规则变一下
可以把新的字母表顺序存储在一个Map中

class Solution {
    public boolean isAlienSorted(String[] words, String order) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < order.length(); i++) {
            map.put(order.charAt(i), i);
        }
        for (int i = 0; i < words.length - 1; i++) {
            if (!less(words[i], words[i + 1], map)) return false;
        }
        return true;
    }

    boolean less(String s1, String s2, Map<Character, Integer> map) {
        int len = Math.min(s1.length(), s2.length());
        for (int i = 0; i < len; i++) {
            char c1 = s1.charAt(i);
            char c2 = s2.charAt(i);
            if (c1 != c2) {
                int a = map.get(c1);
                int b = map.get(c2);
                return a < b;
            }
        }
        return s1.length() == len;
    }
}

由于是字符串而且字母表长度已知为26
所以可以用一个数组存储进行优化

class Solution {
    //字母表每个字母都有一个数字对应着大小
    //例如是地球字母表,i从0开始自增, a-'a'=0, 大小i=0,b-'a'=1, 大小i=1, c-'a'=2,大小i=2,
    //假如外星字母表为"hlabcde...xyz",那 h-'a'= 7,此时大小i=0, l-'a'=10,此时大小i=1一次类推
    public boolean isAlienSorted(String[] words, String order) {
        int[] hash = new int[26];
        for (int i = 0; i < 26; i++) {//存到数组中
            hash[order.charAt(i) - 'a'] = i;
        }
        for (int i = 0; i < words.length - 1; i++) {
            if (!less(words[i], words[i + 1], hash)) return false;
        }
        return true;
    }

    boolean less(String s1, String s2, int[] hash) {
        int len = Math.min(s1.length(), s2.length());
        for (int i = 0; i < len; i++) {
            char c1 = s1.charAt(i);
            char c2 = s2.charAt(i);
            if (c1 != c2) {
                int a = hash[c1 - 'a'];
                int b = hash[c2 - 'a'];
                return a < b;
            }
        }
        return s1.length() == len;
    }
}

566. Reshape the Matrix

转换矩阵为给定的新维度
In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the ‘reshape’ operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.

    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int row = nums.length;
        int col = nums[0].length;
        if (row * col != r * c) return nums;//长度不一致则直接返回原矩阵。
        int[][] reshaped = new int[r][c];//重塑后的矩阵
        for (int i = 0, m = 0, n = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                reshaped[m][n++ % c] = nums[i][j];
                if (n % c == 0) {//当添加个数为c的倍数时,换下一行添加
                    m++;
                }
            }
        }
        return reshaped;
    }

104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

求二叉树的最大深度

	//递归求做子树和右子树的高度,返回较大者
    public int maxDepth(TreeNode root) {
        if(root != null) {
            int left = maxDepth(root.left) + 1;
            int right = maxDepth(root.right) + 1;
            return Math.max(left, right);
        }
        return 0;
    }

136. Single Number

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

有一个非空数组。除了一个特殊的元素只出现一次,其余每个元素都出现了两次。找出那个只出现一次的数

	//解法1,把每个数都放到Set中,如果已经出现过,则减去他。这样,所有成对的数都会消为0.最后的结果即为要寻找的单数
    public int singleNumber(int[] nums) {
        int sum = 0;
        Set<Integer> set = new HashSet<>(nums.length);
        for (int n : nums) {
            if (set.contains(n)) sum -= n;
            else {
                set.add(n);
                sum += n;
            }
        }
        return sum;
    }
    //解法2,用到了异或两次还原的特点,把相同的数消去,非常酷的解法
    public int singleNumber(int[] nums) {
        int r = 0;
        for (int num : nums) {
            r ^= num;
        }
        return r;
    }

429. N-ary Tree Level Order Traversal

Given an n-ary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

For example, given a 3-ary tree:
在这里插入图片描述
We should return its level order traversal:

[
[1],
[3,2,4],
[5,6]
]

遍历树的每一层,把每一层的节点值存到List里
利用队列,实现广度优先遍历

    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {//把当前层的元素遍历一遍,加到List中
                Node node = queue.poll();
                list.add(node.val);
                if (node.children != null) {//把下一层的所有子节点放到队列中,待处理
                    for (Node child : node.children) {
                        queue.offer(child);
                    }
                }
            }
            if (!list.isEmpty()) {
                result.add(list);
            }
        }
        return result;
    }

637. Average of Levels in Binary Tree

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Input:
    3
   / \
  9  20
    /  \
   15   7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3,  on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].

和上一道一样,广度优先遍历
在每一层计算总和,然后求平均

    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            
            double sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            if (size != 0) { 
                list.add(sum / size);
            }
        }
        return list;
    }
根据引用,可以看出这是一段使用迭代器进行循环遍历的代码,并且遍历的对象是`vector<int>`类型的向量。迭代器`it`初始化为`c.begin()`,结束条件为`it < c.end()`。这段代码中省略了循环体,需要根据具体上下文来确定循环体的具体操作。 根据引用,我们可以了解到`vector`是一种动态数组,可以存储多个相同类型的元素。代码示例中用`assign`函数将另一个向量的一部分元素赋值给目标向量。具体来说,`a.assign(b.begin(), b.begin()+3)`意味着将向量`b`的前三个元素赋值给向量`a`。 根据引用,可以看出这是一段关于在VSCode中安装leetcode插件和配置的说明文档。文档中提到了如何安装插件、如何编译和构建代码等内容。 综上所述,LeetCode的`vector`是一种动态数组,可以存储多个相同类型的元素。可以通过迭代器对其进行循环遍历,也可以使用成员函数`assign`来赋值部分元素。在VSCode中,可以安装LeetCode插件并进行相关配置来进行编译和构建。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [C++LeetCode每日一题 Day3 常用容器vector的使用](https://blog.csdn.net/m0_75276704/article/details/129737396)[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: 50%"] - *3* [vscode安装leetcode-Leetcode:力码](https://download.csdn.net/download/weixin_38557935/20051243)[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: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值