Denote Sm = min(a1, b1) + min(a2, b2) + … + min(an, bn). The biggest Sm is the answer of this problem. Given 1, Sm = a1 + a2 + … + an.
Denote Sa = a1 + b1 + a2 + b2 + … + an + bn. Sa is constant for a given input.
Denote di = |ai - bi|. Given 1, di = bi - ai. Denote Sd = d1 + d2 + … + dn.
So Sa = a1 + a1 + d1 + a2 + a2 + d2 + … + an + an + di = 2Sm + Sd => Sm = (Sa - Sd) / 2.
To get the max Sm, given Sa is constant, we need to make Sd as small as possible. So this problem becomes finding pairs in an array that makes sum of di (distance between ai and bi) as small as possible. Apparently, sum of these distances of adjacent elements is the smallest. If that’s not intuitive enough, see attached picture. Case 1 has the smallest Sd.
publicclass Solution {
publicintarrayPairSum(int[] nums) {
Arrays.sort(nums);
int result = 0;
for (int i = 0; i < nums.length; i += 2) {
result += nums[i];
}
return result;
}
}
publicclass Solution {
publicint[][] matrixReshape(int[][] nums, int r, int c) {
int m = nums.length, n = nums[0].length;
if(m*n != r*c){
return nums;
}else {
int[][] result = newint[r][c];
for (int i = 0; i < m * n; i++) {
result[i/c][i%c] = nums[i/n][i%n];
}
return result;
}
}
}
publicclass Solution {
public List<String> fizzBuzz(int n) {
ArrayList<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i%3==0 && i%5==0){
result.add("FizzBuzz");
}elseif(i%3==0){
result.add("Fizz");
}elseif(i%5==0){
result.add("Buzz");
}else {
result.add(i+"");
}
}
return result;
}
}
Average of Levels in Binary Tree
计算二叉树每一层的平均数
对队列的理解
BLF
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/publicclassSolution {public List<Double> averageOfLevels(TreeNode root) {
List<Double> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if (queue == null) return result;
queue.add(root);
while (!queue.isEmpty()) {
int n = queue.size();
double total = 0.0;
for (int i = 0; i < n; i++) {
TreeNode node = queue.poll();
total += node.val;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
result.add(total / n);
}
return result;
}
}
Island Perimeter
计算岛屿周长
对二维数组的理解
对数组下标的理解
publicclass Solution {
publicintislandPerimeter(int[][] grid) {
int islands = 0, neighbours = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
islands++; // count islandsif (i < grid.length - 1 && grid[i + 1][j] == 1) neighbours++; // count down neighboursif (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbours++; // count right neighbours
}
}
}
return islands * 4 - neighbours * 2;
}
}
Hamming Distance 整数的二进制形式 相对应的位置 bit位(0、1)不同的有几位?考察二进制位运算 Integer 与二进制public class Solution { public int hammingDistance(int x, int y) { return Integer.bitCount(x^y); }}Merge Two B