LeetCode第五天
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<size;i++){
newNums[i/c][i%c] = nums[i/nums[0].length][i%nums[0].length];
}
return newNums;
}
}
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<words.length;i++){
if(words[i].equals(word1))
idx1=i;
else if(words[i].equals(word2))
idx2=i;
if(idx1 != -1 && idx2 != -1){
minDistance = Math.min(minDistance,Math.abs(idx1-idx2));
}
}
return minDistance;
}
}
25.(561) Array Partition I
JAVA
class Solution {
public int arrayPairSum(int[] nums) {
Arrays.sort(nums);
int minSum = 0;
for(int i = 0;i<nums.length;i+=2){
minSum += Math.min(nums[i],nums[i+1]);
}
return minSum;
}
}
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) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int[] result;
for(int i = 0;i<nums.length;i++){
if(map.containsKey(target - nums[i])){
return new int[] {map.get(target-nums[i]),i};
}else{
map.put(nums[i],i);
}
}
return null;
}
}
作者:郭耀华
出处:http://www.guoyaohua.com
微信:guoyaohua167
邮箱:guo.yaohua@foxmail.com
本文版权归作者和博客园所有,欢迎转载,转载请标明出处。
【如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐】
出处:http://www.guoyaohua.com
微信:guoyaohua167
邮箱:guo.yaohua@foxmail.com
本文版权归作者和博客园所有,欢迎转载,转载请标明出处。
【如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐】