文章目录
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;
}