其他专题
其他专题
总有一些题目,是使用人类智慧硬解的,当然LC也不太为难你。
一道medium这么低的ac率因为啥,坑多呀。
class Solution { public int myAtoi(String str) { final int space = 32; final int numberStart = 48; final int numberEnd = 57; final char negative = '-'; final int bit =10; int convert = 0; int param = 1; for(int i =0;i<str.length();i++){ int code = (int)str.charAt(i); if(code == space){ continue; }else if(code == negative){ param = -1; }else if(code >= numberStart && code <= numberEnd){ int old = convert; int add = (code - numberStart)*param; convert = convert*bit + add; if(convert - old != add){ if(old < 0){ return Integer.MIN_VALUE; }else { return Integer.MAX_VALUE; } } }else { break; } } return convert; } }
42. Trapping Rain Water
头条同款题目,做的时候完全没准儿,一不小心就过了。
class Solution { public int trap(int[] height) { int left = 0; int summation = 0; int highestIndex = 0; int each = 0; for(int i=0;i<height.length;i++){ if(height[i] >= left){ summation += each; each = 0; left = height[i]; highestIndex = i; }else { each += (left - height[i]); } } int summationRevert = 0; left = 0; each = 0; for(int i=height.length-1;i>=highestIndex;i--){ if(height[i] >= left){ summationRevert += each; each = 0; left = height[i]; }else { each += (left - height[i]); } } return summation+summationRevert; } }
41. First Missing Positive
这道题说起规律,那么就是计数排序的思想了,因为它要求On space。
首先数组下标就是一个排序,每一个数对应下标,那么哪个缺失就知道了。
比如1,2,4,5,6。你在排序的时候,1对应下标1,2对应下标2,3没有对应,那么3就是first missing。
class Solution { public int firstMissingPositive(int[] nums) { if(nums.length == 0){ return 1; } for(int i=0;i<nums.length;i++){ if(nums[i] > 0 && nums[i]<nums.length && nums[i] != i+1){ int temp = nums[nums[i] - 1]; if(temp == nums[i]) continue; nums[nums[i] - 1] = nums[i]; nums[i] = temp; i--; } } int minPositive = 0; for(int i=0;i<nums.length;i++){ if(nums[i] != i + 1){ return i + 1; }else { minPositive = i + 1; } } return minPositive + 1; } }
48. Rotate Image
将一张图片向右转90度。
先将矩阵转置,然后垂直取镜像。
class Solution { public void rotate(int[][] matrix) { for(int i=0;i<matrix.length;i++){ for(int j=1;j<matrix[i].length;j++){ if(i+j >= matrix[i].length || i+j >= matrix.length){ break; } int temp = matrix[i][i+j]; matrix[i][i+j] = matrix[i+j][i]; matrix[i+j][i] = temp; } } for(int i = 0;i<matrix.length;i++){ int left = 0; int right ; while(left < (right = matrix[i].length-left - 1)){ int temp = matrix[i][left]; matrix[i][left] = matrix[i][right]; matrix[i][right] = temp; left ++; } } } }