892. 三维形体的表面积
class Solution {
public int surfaceArea(int[][] grid) {
int n = grid.length, area = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// 先把grid[i][j]赋值给level,省掉了bound check,可以略微略微略微优化一下耗时...
int level = grid[i][j];
if (level > 0) {
// 一个柱体中:2个底面 + 所有的正方体都贡献了4个侧表面积
area += (level << 2) + 2;
// 减掉 i 与 i-1 相贴的两份表面积
area -= i > 0? Math.min(level, grid[i - 1][j]) << 1: 0;
// 减掉 j 与 j-1 相贴的两份表面积
area -= j > 0? Math.min(level, grid[i][j - 1]) << 1: 0;
}
}
}
return area;
}
}
class Solution {
public int surfaceArea(int[][] grid) {
int[] dr = new int[]{0, 1, 0, -1};
int[] dc = new int[]{1, 0, -1, 0};
int N = grid.length;
int ans = 0;
for (int r = 0; r < N; ++r)
for (int c = 0; c < N; ++c)
if (grid[r][c] > 0) {
ans += 2;
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k];
int nc = c + dc[k];
int nv = 0;
if (0 <= nr && nr < N && 0 <= nc && nc < N)
nv = grid[nr][nc];
ans += Math.max(grid[r][c] - nv, 0);
}
}
return ans;
}
}
面试题56 - I. 数组中数字出现的次数
class Solution {
public int[] singleNumbers(int[] nums) {
Set<Integer> set = new HashSet<>();
int[] res = new int[2];
int k = 0;
for (int n : nums) {
if(set.contains(n)){
set.remove(n);
}else{
set.add(n);
}
}
for (int a : set) {
res[k++] = a;
}
return res;
}
}
class Solution {
public int[] singleNumbers(int[] nums) {
int sum=0;
//得到异或结果,即为不相同两个数的异或结果sum
for(int num:nums)
sum^=num;
//得到sum的二进制的1的最低位
int flag=(-sum)∑
int result[]=new int[2];
//分成两个组进行异或,每组异或后的结果就是不相同两个数的其中之一
for(int num:nums){
if((flag&num)==0)
result[0]^=num;
else{
result[1]^=num;
}
}
return result;
}
}
class Solution {
public int[] singleNumbers(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int n : nums) {
if (set.contains(n))
set.remove(n);
else
set.add(n);
}
return set.stream().mapToInt(Integer::intValue).toArray();
}
}
面试题52. 两个链表的第一个公共节点
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode h1 = headA, h2 = headB;
while (h1 != h2) {
h1 = h1 == null ? headB : h1.next;
h2 = h2 == null ? headA : h2.next;
}
return h1;
}
}
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headB==null||headA==null) return null;
ListNode cur1=headA,cur2=headB;
int n=0;
while(cur1!=null){
n++;
cur1=cur1.next;
}
while(cur2!=null){
n--;
cur2=cur2.next;
}
cur1=n>0?headA:headB;
cur2=cur1==headA?headB:headA;
n=Math.abs(n);
while(n>0){
cur1=cur1.next;
n--;
}
while(cur1!=cur2){
cur2=cur2.next;
cur1=cur1.next;
}
return cur1;
}
}
你知道的越多,你不知道的越多。
有道无术,术尚可求,有术无道,止于术。
如有其它问题,欢迎大家留言,我们一起讨论,一起学习,一起进步