leetcode 第五天
2018年1月6日
22.(566) Reshape the Matrix
JAVA
class Solution { public int[][] matrixReshape(int[][] nums, int r, int c) { int[][] newNums = new int[r][c]; int size = nums.length*nums[0].length; if(r*c != size) return nums; for(int i=0;i
23.(268) Missing Number
JAVA
class Solution { /*数列求和思想*/ public int missingNumber(int[] nums) { int expectSum = nums.length*(nums.length+1)/2; int actualSum = 0; for(int num : nums) actualSum += num; return expectSum - actualSum; }}
24.(243) ==Shortest Word Distance==
JAVA
class Solution { public int shortestDistance(String[] words,String word1,String word2) { int idx1 = -1,idx2 = -1; int minDistance = words.length; int currentDistance; for(int i =0;i
25.(561) Array Partition I
JAVA
class Solution { public int arrayPairSum(int[] nums) { Arrays.sort(nums); int minSum = 0; for(int i = 0;i
26.(746) ==Min Cost Climbing Stairs==
==新知识点:动态规划(有点难度)==
JAVA
class Solution { public int minCostClimbingStairs(int[] cost) { int f1=0; int f2=0; int f3=0;//f3为到达每一个楼层所需要花费的最小钱数(此楼层花费不算) for(int i = 2;i <= cost.length;i++){ f3 = Math.min(f1+cost[i-2],f2+cost[i-1]); f1 = f2; f2 = f3; } return f3; }}
27.(724) Find Pivot Index
JAVA
class Solution { public int pivotIndex(int[] nums) { int sum = 0,leftSum = 0; for(int num : nums) sum+=num; for(int i = 0;i < nums.length;i++){ if(leftSum == sum - leftSum - nums[i]) return i; leftSum += nums[i]; } return -1; }}
28.(66) Plus One
JAVA
class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for(int i = n-1;i>=0;i--){ if(digits[i]<9){ digits[i]++; return digits; } digits[i] = 0; } //此处是为了防止原始数字为999...的情况 int[] result = new int[n+1]; result[0] = 1; return result; }}
29.(1) Two Sum
==注意Map/HashMap的声明、get()/containsKey()/put()等操作==
JAVA
class Solution { public int[] twoSum(int[] nums, int target) { Mapmap = new HashMap (); int[] result; for(int i = 0;i